简体   繁体   中英

Unhandled Rejection (TypeError): setDailyData is not a function

I have an error in below code and I don't know what should I do.

const { dailyData, setDailyData } = useState([]);

useEffect(() => {
    const fetchAPI = async () => {
    setDailyData(await fetchDailyData());
};

    fetchAPI();
  });

Error

The issue with your code is that you are extracting the properties from useState incorrectly.


The useState function returns an array , from which you destructure the properties by index.

To destructure the returned value of useState , you need to use square brackets ( [] ) instead of curly braces ( {} ).

So, the fixed code would look like so.

const [dailyData, setDailyData] = useState([]);

This will assign the values of the array to the variables as so.

Index Variable
0 dailyData
1 setDailyData

In conclusion, you have to destructure the useState return value by index (eg 0 , 1 , etc.), instead of by name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM