Search code examples
javascriptreactjsantd

How can i update a useState from an array?


Why does not work the useState for array? i am passing a object for props, now i am printing inside of useEffect his value, at the console.log it have the correct value that value is an array. i catch that array then i tryed to update the usestate but does not worked

const ComponentHeader = ({ csp }) => {
  const [materials, setMaterials] = useState(null)
  useEffect(() => {
      const { mat } =csp

      console.log('Console...', mat)
      setMaterials(mat)
  }, [csp])

in the template: i am using antd to show in a list

return (
 {materials && (
            <Form.List initialValue={materials}>

i put a console inside of useEffects

useEffect(() => {
      const { mat } =cp
      console.log('HEEERRREEE', mat)
      
  }, [])

this is the output:

jsx:26 HEEERRREEE { mat: Array(1)}
jsx:26 HEEERRREEE { mat: Array(2)}

should print 2 elements, but only print 1 element


Solution

  • The useEffect is a hook that handles side effects, and having this second array parameter allows side effects to be run whenever any value changes. so you need to check if csp is changing. Hope this answer your question thanks!