Home > Mobile >  How can i resolve the syntax error from this code
How can i resolve the syntax error from this code

Time:04-24

running the code below throws a syntax error in the console. it points to the spread operator as an error , please how do i fix it?

import {useState} from "react";

    const [dataInput,setDataInput] = useState({ name: "", age: "", id: "" });
        const nameChangeHandler = (event) =>{
        setDataInput((previousDataInput)=>{...previousDataInput, name:event.target.value})
    }
    return (
        <div>
            <label>Username</label>
            <input type="text" onChange={nameChangeHandler} />
            <label>Age (Years)</label>
            <input type="number" />
        </div>
    );
};
export default FormInputs;```



This is the error

Failed to compile.

./src/components/Form/FormInputs.js
SyntaxError: C:\Users\User\Desktop\Programs\React\academind\src\components\Form\FormInputs.js: Unexpected token (6:37)

  4 |   const [dataInput,setDataInput] = useState({ name: "", age: "", id: "" });
  5 |           const nameChangeHandler = (event) =>{
> 6 |           setDataInput((previousDataInput)=>{...previousDataInput, name:event.target.value})
    |                                              ^
  7 |   }

CodePudding user response:

You must return an object in setDataInput, not an arrow function

CodePudding user response:

To return an object literal expression requires parentheses around expression:

params => ({foo: "a"}) // returning the object {foo: "a"}

Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

As the doc says if you want to return an object literal expression without the return keywoard you need to enclose the object inside parentheses:

setDataInput((previousDataInput)=>({...previousDataInput, name:event.target.value}))

Alternatively you can use the return keywoard like this:

setDataInput((previousDataInput)=>{
 return {...previousDataInput, name:event.target.value};
})
  • Related