Ayan
Ayan

Reputation: 181

React state is not updating object

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;

Upvotes: 1

Views: 640

Answers (1)

arbitrary_A
arbitrary_A

Reputation: 373

[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

Upvotes: 2

Related Questions