Search code examples
react-nativeuse-effect

Comma expected error in useEffect data React


I got "," (comma) expected error from data: {...sample.data, res.data} the error points to dot "." of res.data

useEffect(()=>{
     axios.get('http://localhost:1234/hello').then((res)=>{
          {console.log(res.data)}
          setSample({
            ...sample,
            data: {...sample.data, res.data}
          })
          {console.log(sample)}
     })
  }, [])

Solution

  • You will have to spread the res.data too.. Consider the below example

      const [sample, setSample] = useState({data: {value: 'initial'}});
    
      useEffect(() => {
        const res = {
          data: {
           another_value: "from api"
          }
        };
    
        setSample({
          ...sample,
          data: { ...sample.data, ...res.data }
        });
        
      }, []);
    

    The initial state of sample has property value with value = initial. In the useEffect, we are adding one more value to the sample object. This will result in an output,

    {value: "initial", another_value: "from api"}
    

    also the console.log(sample) won't show the updated value if you log it just below the setSample. You might wanna add a useEffect with sample as dependency and it will listen to the changes in sample.

      useEffect(() => {
        console.log(sample);
      }, [sample]);