简体   繁体   中英

How to update initstate's value's array using useState?

I Want to update categories array's value/ insert categories json data into after fetching categories from DB. But can't find the right way ? Note: Please check the loadCategories function.

import React, {useEffect, useState} from "react";
import {getCategories} from "../../../Functions/Categoy";

const initialState = {
    title:"",
    desc:"",
    colors:["Black", "Brown", "Silver", "White", "Blue"],
    categories:[] // here to insert
}

const CreateProducts = () => {

    const [data, setData] = useState([initialState]);

    const { title, desc, colors, categories } = data
  
    useEffect(() => {
        loadCategories();
    }, [])
  
    const loadCategories = () => {
        getCategories()
                .then((res) => {
                    // here I want to insert/update categories value
                    // setData({ prevState =>  [...prevState, categories : res.data] })
                })
    };

    return (
          <div>{JSON.stringify(categories)}</div>
)}

export default CreateProducts;
  1. "Categoy" is probably a typo? It should be "Category".

  2. No need to add initialState in an array to useState .

  3. async/await makes life a little less complicated when working with data returned by fetch . You can add an async function to useEffect and have that fetch your data, parse it, and then update your component state.

  4. You can then map over the categories in state (or whatever you want to do) to produce your JSX.

An updated example.

import React, {useEffect, useState} from 'react';
import {getCategories} from '../../../Functions/Category';

const initialState = {
    title: '',
    desc: '',
    colors: ['Black', 'Brown', 'Silver', 'White', 'Blue'],
    categories: []
};

function CreateProducts() {

  const [data, setData] = useState(initialState);

  useEffect(() => {
    async function loadCategories() {
      const res = await getCategories();
      const categories = await res.json();
      setCategories({ ...data, categories });
    }
    loadCategories();
  }, [])

  return (
    <div>
      {data.categories.map(category => <div>{category}</div>)}
    </div>
  );

}

export default CreateProducts;

try this instead

import React, {useEffect, useState} from "react";
import {getCategories} from "../../../Functions/Categoy";

const initialState = []

const CreateProducts = () => {

    const [data, setData] = useState(initialState);

    useEffect(() => {
        loadCategories();
    }, [])

    const loadCategories = () => {
        getCategories()
            .then((res) => {
                 setData([...data,...res.data])
            })
      };

      return (
           <div>{JSON.stringify(data)}</div>
      )}

export default CreateProducts;

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