skip to Main Content

I want to copy only those property which is already declared in useState array, like this:

const SellDashBoard = () => {
  const[userData, setUserData] = useState({
    name: '',
    age: '',
    number: '',
  })

  const data = {
    name: 'Ram',
    age: '21',
    village: 'pithawaiaya'
  }

  useEffect(() => {
    setUserData((pre) => {
      return { ...pre, ...data }
    })
  }, [])

  return (
    <div>
      
    </div>
  )
}

The result is: { name: "Ram", age: "21", number: "", village: "pithawaiaya" }

I want result as userData { name: "Ram", age: "21", number: "" }.

4

Answers


  1. Your excpected output state you wanna be excact similar with your data obj, so the best solution i think is to declare the data obj in your current useState and delete the useEffect hook.

      const data = {
        name: 'Ram',
        age: '21',
        village: 'pithawaiaya'
      }
    
    const SellDashBoard = () => {
      const[userData, setUserData] = useState(data)
    
      return (
        <div>
         
        </div>
      )
    }
    

    You will place the data obj outside from your componentSellDashBoard or you can move it in outside file and you can import it as well.

    Login or Signup to reply.
  2. useEffect(() => {
    setUserData((pre) => {
      return { ...pre, name: data.name,age:data.age }
    })
    }, [])
    

    Keep every other thing in the object the same and update only the other attributes that you want to change.

    We can also make a function that returns an updated object and then we can use useState to update new object. All we are doing in the method is comparing the two objects with the keys and if the key exists in the useState object then simply update that and leave everything else. I think this should do the job.

       function updateObject(finalObj, data) {
        for (const key in finalObj) {
          if (data.hasOwnProperty(key)) {
            finalObj[key] = data[key];
          }
        }
        return finalObj;
      }
    useEffect(() => {
        const updatedObj =updateObject(userData,data)
        setUserData({...updatedObj})
      }, [])
      console.log("finally",userData)
    
    Login or Signup to reply.
  3. Instead of shallow copying all of the data object’s properties into the userData state, create a shallow copy of the previous state to update and iterator over the data object’s keys to explicitly check if it is a property of the state, and if it is, overwrite the property.

    Example:

    const [userData, setUserData] = useState({
      name: "",
      age: "",
      number: ""
    });
    
    useEffect(() => {
      setUserData((pre) => {
        const nextState = { ...pre };
    
        for (const key in data) {
          if (nextState.hasOwnProperty(key)) {
            nextState[key] = data[key];
          }
        }
    
        return nextState;
      });
    }, []);
    
    const data = {
      name: "Ram",
      age: "21",
      village: "pithawaiaya"
    };
    
    const SellDashBoard = () => {
        const [userData, setUserData] = React.useState({
        name: "",
        age: "",
        number: ""
      });
    
      React.useEffect(() => {
        setUserData((pre) => {
          const nextState = { ...pre };
    
          for (const key in data) {
            if (nextState.hasOwnProperty(key)) {
              nextState[key] = data[key];
            }
          }
    
          return nextState;
        });
      }, []);
    
      return (
        <div>
          {JSON.stringify(userData)}
        </div>
      )
    }
    
    const rootElement = document.getElementById("root");
    const root = ReactDOM.createRoot(rootElement);
    
    root.render(
      <SellDashBoard />
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js"></script>
    <div id="root" />
    Login or Signup to reply.
  4. You can create a function that will check if the key in useState exist in data then copy it if not then empty string. Try this implementation

    setUserData((prev) => {
          // convert the previous data to array of keys
          const dataKeys = Object.keys(prev);
          // create new instance of an object
          let newData = {};
          for (let key of dataKeys) {
            /* 
              this is to check if keys in previous state exist in new data.
              if exist then copy if not empty string
            */ 
            newData = { ...newData, [key]: data[key] ?? "" };
          }
          return newData;
        });
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search