简体   繁体   中英

How can i set state value after destructing in React Hooks?

I tried to destructure and set the value in state using React Hooks,but their it shows a syntax error.Since i am new on react JS,please help me for the solution.

Following below is my code:

I set the state as following:

const [Datasets, setDatasets] = useState({
  labels: [],
  datasets: [{
      label: 'Total Cases',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(100,19,12,1)',
      borderColor: 'green',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Recovered',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    },
    {
      label: 'Total Deaths',
      fill: false,
      lineTension: 0.5,
      backgroundColor: 'rgba(75,192,192,1)',
      borderColor: 'rgba(0,0,0,1)',
      borderWidth: 2,
      data: []
    }
  ]
})

I used useEffect to fetch data from API and set state.Following are my codes on useEffect:

useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets({ ...Datasets, labels: res.data.map((item) => item.date) })
      setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])
        .catch(err => {
          console.log("error>>", err);
        })
    })

when i try to run the code the error is shown in the following code:

setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)])

following error is shown:

在此处输入图像描述

following are the data i have fetched from the API:

在此处输入图像描述

Please help me for the solution.

[Datasets.datasets[0].data: res.data.map((item) => item.totalCases)] of of setDatasets([Datasets.datasets[0].data: res.data.map((item) => item.totalCases)]) is an array, you can not have : in array like that. Try this:

 useEffect(() => { axios.get('https://data.nepalcorona.info/api/v1/covid/timeline').then(res => { setTimelinedata(res.data) const labels = res.data.map((item) => item.date) const data = res.data.map((item) => item.totalCases) setDatasets({ labels: res.data.map((item) => item.date, [{...Datasets.datasets[0], data: data}, ...Datasets.datasets])}).catch(err => { console.log("error>>", err); }) })

Unlike class-based components' setState , the functional components' useState hook does not merge state updates into existing state, this needs to be done manually.

NOTE: Don't forget to add a dependency array so the effect isn't triggered each render by the state update and cause an infinite loop. Empty array will trigger the effect when the component mounts, but you can add others if you need to update dataset later after component has been mounted, similar to componentDidUpdate lifecycle function from class-based components.

useEffect(() => {
  axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
    .then(res => {
      setTimelinedata(res.data)
      setDatasets(Datasets => { // <-- Use a functional state update since next state could depend on previous state
        const labels = [
          ...Datasets.labels, // spread in existing labels
          ...res.data.map((item) => item.date) // spread in new labels
        ];

        const datasets = [
          ...Datasets.datasets, // spread in existing datasets
        ];

        // Now you can copy the total cases into the first index.
        datasets[0].data = res.data.map((item) => item.totalCases);

        return {
          ...Datasets, // spread in existing state
          labels,
          datasets,
        };
      });
    .catch(err => {
      console.log("error>>", err);
    });
}, []); // <-- Empty dependency array to run once, on mount

Please useEffect with below one. Moreover, you should use empty dependency array [] as an second parameter in useEffect to run api once. Moreover, you missed to put }) before catch

useEffect(() => {
        axios.get('https://data.nepalcorona.info/api/v1/covid/timeline')
            .then(res => {
                setTimelinedata(res.data);
                setDatasets({...Datasets, labels: res.data.map((item) => item.date)});
                let newDatasets = {...Datasets};
                newDatasets.datasets[0].data = res.data.map((item) => item.totalCases);
                newDatasets.datasets[1].data = res.data.map((item) => item.newRecoveries);
                newDatasets.datasets[2].data = res.data.map((item) => item.totalDeaths);
                setDatasets({...Datasets, ...newDatasets});

                console.log(Datasets, 'datasets');
            })
            .catch(err => {
                console.log("error>>", err);
            })
    }, []);

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