Home > Software design >  Unable to set default value for array in use state
Unable to set default value for array in use state

Time:11-05

I want to set default value to my state, but it's getting undefined. But if I refresh my page values get assigned to categoryIds.


  const si = [...searchParams.getAll("cat")];
  console.log("si", si);

  let sinew = [];
  si.forEach((c) => {
    sinew.push(catmap2.get(c));
  });
  console.log("sinew", sinew);  //print sinew correctly with ids

 

  const [categoryIds, setCategoryIds] = useState(si.length==0? [] : sinew);

  console.log("catids", categoryIds);   //It gives array of same size as sinew but with undefined values

I have also tried to set it using useEffect but got same issue.

useEffect(() => {
    console.log(sinew);  //prints correctlty
    setCategoryIds(sinew);  // but CategoryIds still have undefined values
  }, []);

Output

CodePudding user response:

You're trying to set the initial state of categoryIds with the value of sinew. However, sinew is a derived value from si which is also derived from searchParams.getAll("cat"). If searchParams.getAll("cat") is asynchronous or depends on some other state or props, then sinew and categoryIds might not be set correctly during the first render.

You said you try to use the useEffect hook to update the state when the sinew value changes. However, you should ensure that sinew is not changing during the component's lifecycle, otherwise, it will cause an infinite loop.

Then, How?

The below is the sample execution that I can give to help you.

const [categoryIds, setCategoryIds] = useState([]);

useEffect(() => {
 const si = [...searchParams.getAll("cat")];
 let sinew = [];
 si.forEach((c) => {
   sinew.push(catmap2.get(c));
 });
 setCategoryIds(sinew);
}, [searchParams]);

Here, the useEffect will run every time searchParams changes, and it will update categoryIds with the new sinew value.

However, if searchParams.getAll("cat") is synchronous and you're sure that sinew is not changing during the component's lifecycle, you should check if catmap2.get(c) is returning undefined for some c in si. This could be the reason why you're seeing undefined values in categoryIds.

  • Related