Home > other >  React state is not updating object
React state is not updating object

Time:02-25

Here first I have a static object which has three values and I have created a form where I am taking input from user and then I wanna merge that new input with already created static object but it is not working although if I console to check whether values are merged are not then in console results are according to my exception but while rendering its not working on output screen I am just getting three static values here is my code:

import React, {useState} from "react";

import Expenses from './components/Expenses/Expenses.js';
import NewExpense from './components/NewExpense/NewExpense.js';

  let my_expenses = [
    {
      title : "Scholarship Fee",
      date : new Date(2021, 11, 24),
      amount : '$1000'
    },
    {
      title : "Sports Fee",
      date : new Date(2021, 1, 14),
      amount : '$200'
    },
    {
      title : "Extra",
      date : new Date(2021, 10, 8),
      amount : '$100'
    }
  ];

const App = () =>{
  const [expenses, setExpenses] = useState(my_expenses);

  const newExpenseData = (data) => {
    const updatedExpenses = [data, ...expenses];
    setExpenses(updatedExpenses);
  }
  return (
    <div>
      <NewExpense newExpenseData = {newExpenseData}/>
      <Expenses item={my_expenses}/>
    </div>
  );
}

export default App;

CodePudding user response:

[Using spread operator while merging]    

let p = {x: 12, y: 34}
let q = {z: 56}

let mergedObj = {...p, ...q} // works as union
console.log(mergedObj) // { x: 12, y: 34, z: 56 }

hope it will help you to understand further step

CodePudding user response:

You are not displaying the data of the state expenses, but my_expenses, which is your static object, in the component Expenses.

In NewExpense you are providing a function newExpanseData that gets data as an input argument and then updates the state expenses by merging data with its previous values. This is fine.

However, if newExpenseData is called, then this will trigger a rerender but since you are not showing expenses, but my_expenses, nothing will visually change.

Here is what you need to change.

const [expenses, setExpenses] = useState(my_expenses);

  const newExpenseData = (data) => {
    const updatedExpenses = [data, ...expenses];
    setExpenses(updatedExpenses);
  }
  return (
    <div>
      <NewExpense newExpenseData = {newExpenseData}/>
      <Expenses item={expenses}/>
    </div>
  );

The state expenses gets my_expenses as initial data, thus on first rendering your static object will be visible. If you call the function newExpenseData, then data will be appended to expenses which will cause a rerendering but this time we display expenses instead of my_expenses.

  • Related