skip to Main Content

The parent component doesn’t seem to access the ErrorMessage I get this error…

Objects are not valid as a React child (found: object with keys {error_msg}). If you meant to render a collection of children, use an array instead.

I checked and error_msg is the error message.

in the parent component I have…

function App() {

const [ErrorMessage, setErrorMessage] = useState('');

 const handleClickUpdate = async (event) => {
 
       ...
    const error_msg = Validation(postData)  
    setErrorMessage(error_msg)
   ...
 }
   <button type="submit" onClick={() => 
 handleClickUpdate({stuff})}>Update</button>


return (
     <div>
         <Submit setSomethingElse={somethingElse} setErrorMessage={(error) =>setErrorMessage(error)} ErrorMessage={ErrorMessage} />
     </div>
   <div className="error-message"> {ErrorMessage}</div>
 );

}

So in the child component:

  function Submit({ setSomethingElse, setErrorMessage, 
  ErrorMessage }) {



 const handleSubmit = async (event) => {

     ...
      setErrorMessage('Error Message')
     ...

}

But errorMessage is empty even after the assignment. Am I not passing in the prop correctly?

  return (
     <form onSubmit={handleSubmit}>
        ...           
        <div>{ErrorMessage}</div>
     </form>
       );

}

2

Answers


  1. The parent would need to pass not just the state setter, but also the state getter/value.

    function App() {
    
    const [errorMessage, setErrorMessage] = useState('');
    
    
      
    return (
         <div>
             <Submit setErrorMessage={setErrorMessage} errorMessage={errorMessage}/>
         </div>
     );
    
    }
    
    

    and then have the child handle that prop like so..

    function Submit({ setErrorMessage, errorMessage }) {
    
    
    
     const handleSubmit = async (event) => {
    
         ...
          setErrorMessage('Error Message')
         ...
    
    }
    
      return (
         <form onSubmit={handleSubmit}>
            ...           
            <div>{errorMessage}</div>
         </form>
           );
    
    }
    
    Login or Signup to reply.
  2. Instead of passing the function directly as a prop can you try this:

    function App() {
    
    const [errorMessage, setErrorMessage] = useState('');
    
    
      
    return (
         <div>
             <Submit setSomethingElse={somethingElse} setErrorMessage={(error) =>setErrorMessage(error)} errorMessage={errorMessage} />
         </div>
     );
    
    }

    And in the child component you can just use the function like you are already doing.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search