Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

225
Views
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;
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

  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;
about 4 years ago · Juan Pablo Isaza Report

0

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;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!