简体   繁体   中英

i can't save UseState get api in React

This is my output that I get from this GET url: https://localhost/get-all but I can't save this value in the useState: const [dataCat, setDataCat] = useState([]) When I display it in the console, it is displayed correctly, but it returns an empty array in the state

{
  "categories": [
      {
          "id": 1,
          "name": "test1",
          "slug": "intelligence-and-memory-tests",
          "description": null,
      },
      {
          "id": 2,
          "name": "test2",
          "slug": "occupational-and-organizational-tests",
          "description": null,
      },
      {
          "id": 3,
          "name": "test3",
          "slug": "love-and-marriage-tests",
      },
  ]
}

this is my useEffect:

  useEffect(() => {
    const fetchData = async () =>{
      try {
        const {data} = await axios.get('https://localhost/get-all');
        console.log(data);
        setDataCat(data)
      } catch (error) {
        console.error(error.message);
      }
    }
  
    fetchData();
  }, []);

You can display it like this, and it will store the data in your useState() . I've created that formattedData to recreate your object

import { useEffect, useState } from "react";
import axios from "axios";
import "./styles.css";

export default function App() {
  const [dataCat, setDataCat] = useState([]);
  const [newDataCat, setNewDataCat] = useState([]);
  // console.log("dataCat", dataCat);
  // console.log("newDataCat", newDataCat);

  const formattedData = (infoData) => {
    let newDataCat = [];
    infoData.forEach((item) =>
      newDataCat.push({
        id: item.id,
        name: item.name,
        slug: item.slug,
        description: item.description
      })
    );
    return newDataCat;
  };

  useEffect(() => {
    const fetchData = async () => {
      try {
        const { data } = await axios.get(
          "https://localhost/get-all"
        );
        setDataCat(data.categories);
      } catch (error) {
        console.error(error.message);
      }
    };

    fetchData();
  }, []);

  useEffect(() => {
    const cat = formattedData(dataCat);
    setNewDataCat(cat);
  }, [dataCat]);

  return (
    <>
      {newDataCat &&
        newDataCat.map((item) => {
          return (
            <>
              <h2>{item.id}</h2>
              <h2>{item.name}</h2>
              <h2>{item.slug}</h2>
            </>
          );
        })}
    </>
  );
}

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