Home > Net >  How to update/add new data to react functional component object?
How to update/add new data to react functional component object?

Time:11-16

I am trying to create a function that updates an object in react functional component. What i was trying to do is:

  const [content, setContent] = useState({});
  const applyContent = (num:number,key:string,val:string) => {
    if (content[num] === undefined) {
      content[num] = {};
    }
    content[num][key] = val;
    setNewContent(newInput);
  }

But I keep getting an error stating that content doesnt have a num attribute, In vanilla JS it would work, what am i missing to make it work with react functional component?

CodePudding user response:

The setter for your component state has been incorrectly spelled. Have a look at the code below.

import React, { useState } from 'react';
import './style.css';

export default function App() {
  const [content, setContent] = useState({});

  const applyContent = (num, key, val) => {
    //gets the appropriate inputs
    let updatedContent = content;
    let value = {};
    value[key] = val;

    updatedContent[num] = value; //this inserts a new object if not present ot updates the existing one.

    setContent({ ...updatedContent });
  };

  return (
    <div>
      <h1>Click buttons to change content</h1>
      <p>{JSON.stringify(content)}</p>
      <button onClick={(e) => applyContent(0, 'a', 'b')}>Add</button>
      <button onClick={(e) => applyContent(1, 'c', 'd')}>Add</button>
      <button onClick={(e) => applyContent(0, 'e', 'f')}>Add</button>
    </div>
  );
}

CodePudding user response:

content is a read only value. You must not directly mutate this. Use it only to show data or to copy this data to another helper value.

setContent is a function that sets content.

There are two ways to set data

setContent(value) <-- set directly 
setContent(prevState => {
    return {
        ...prevState,
        ...value
    }
})

In second example, you will use the previous value, copy it, and then override it with new value. This is useful if you are only updating a part of an object or array.

If you you are working with a deeply nested object, shallow copy might not be enough and you might need to deepcopy your content value first. If not, then use the prevState example to only update the part of that content

const [content, setContent] = useState({});

const applyContent = (num:number,key:string,val:string) => {
const newContent = {...content} // Shallow copy content
    if (content[num] === undefined) {
      //content[num] = {}; <-- you cant directly change content. content is a readOnly value
    newContent[num] = {}
    
    }
    newContent[num][key] = val;
    //setNewContent(newInput);
      setContent(newContent) // <-- use "setContent" to change "content" value
  }

  • Related