Home > Blockchain >  How to update initstate's value's array using useState?
How to update initstate's value's array using useState?

Time:11-10

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;

CodePudding user response:

  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;

CodePudding user response:

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;
  • Related