user14539016
user14539016

Reputation:

React add to props object

I have a component that uses a prop that recieves data from its parent. I need to edit the value of the prop Im not sure if its possible. I tried using state to copy

const Form = ({ details, form }) => {
   useEffect(() => {
      details.name = 'greg'
   }, [])
}

Is it possible to do something like this? I get an error something like object is not extensible.

Upvotes: 0

Views: 36

Answers (1)

vighnesh153
vighnesh153

Reputation: 5388

Assuming, details is a state variable, you can't update state that way. State is supposed to be immutable. To update state, you can do something like:

import React, {useState, useEffect} from "react";

const Parent = () => {
  const [form, setForm] = useState({});
  const [details, setDetails] = useState({ name: "bill" });
  
  return (
    <Form details={details} form={form} setDetails={setDetails} />
  );
};

const Form = ({ details, form, setDetails }) => {
  useEffect(() => {
    setDetails({
      ...details,
      name: "greg",
    });
  }, []);
  
  return (
    <div>Hello</div>
  );
}

Upvotes: 1

Related Questions