Search code examples
reactjsreact-hooksreact-functional-component

How to find the length of a state in a react component


There is a function as follows:

async function validate(value) { 
    try {
      const result = await schema.validate(value, { abortEarly: false });
      console.log(result);
      return result;
    } catch (error) {
      console.log(error.errors);
      setError({errors:error.errors});
      console.log(setError.length);
    }    
  }

In line number 8, the errors are updated in the state without any problem, but when I want to find the length of the state setError array, it returns the value of 1, even though the value of the created array is greater than 1. Is there a solution to find the state length in functional components in react?


Solution

  • If you want to use the length states, you must pass the array to the secondary state, then find the length from the primary state.

    My problem is solved In fact, I should write as follows

    async function validate(value) {
    try {
    const result = await schema.validate(value, { abortEarly: false });
    setError([]);
    return result;
    } catch (error) {
    setError(error.errors);
    }
      }
    

    The main problem of my code was that I had not transferred the answer of the function to the result correctly The problem was in the following line

    const result = await validate(account);
    

    I was then able to use result