how to update nested object using react and json-server

286 views Asked by At

I really need some help I am trying to figure out the issue for three days but no luck so if you can help I would really appreciated ....I am trying to build a simple app with react and json-server for back end the issue I am having the data has nested object so when even I fetch the data and try to modified it is throw error says the kay in nested obj undefined !! the question how to update the state has nested obj the is the user state const [getUser, setGetUser] = useState({ first_name: '', last_name: '', age: '', gender: '', address: { address1: '', address2: '', city: '', state: '', zip: '' }, order_total: { amount: 0 }, }); and this how onChnage fun works setGetUser({ ...getUser, [e.target.name]: e.target.value }) let see I want to update city in address obj how I can do that

1

There are 1 answers

0
Coot3 On

When you write:

setGetUser({ ...getUser, [e.target.name]: e.target.value })

You are adding a new key value pair to the dictionary, not updating an existing one. If you want to update an existing key value pair, for example the city, you should try the following:

  • Clone the dictionary
  • Amend the clone with the new info
  • setState(amended cloned dictionary)

Eg:

  const [getUser, setUser] = useState({
    first_name: "",
    last_name: "",
    age: "",
    gender: "",
    address: {
      address1: "",
      address2: "",
      city: "",
      state: "",
      zip: ""
    },
    order_total: {
      amount: 0
    }
  });

const updateCityHandler = (city) => {
    let newDict = {...getUser}
    newDict.address.city = city
    setGetUser(newDict)
}