1
    import React, { useState } from 'react'

export default function App() {
  const [todos , set_todos] = useState([''])
  const [input , set_input] = useState('')
  const new_todo = (event) =>{
    set_todos = ([...todos,input]);
  }
  return (
    <>
      <h1>hello world</h1>
      let input = <input value={input} onChange={event=> set_input(event.target.value)}/>
      
      <button onClick ={new_todo}>add todo</button>
      <ul>
        {todos.map(todo =>(
          <li>{todo}</li>
        ))}
      </ul>
      
    </>
  )
}

the error is in 7th line of the code

i am a totally new beginner so it would be helpful if you explain it to me

4
  • 1
    why yu declare let input = <input ... in return? Commented Jun 15, 2021 at 9:27
  • You are trying to override the const value, that is causing the issue Commented Jun 15, 2021 at 9:33
  • Please explain your use-case Commented Jun 15, 2021 at 9:34
  • remove equal operator on line 7 => set_todos([...todos,input]); Commented Jun 15, 2021 at 9:39

2 Answers 2

1

If you want to update your state (that is an array) in react hooks, you should try like this :

  const new_todo = (input) => set_todos(oldState => [...oldState,input])

with this code, you will not see any error but I have some offer for your code that make it better:

  • put your inputs such as input and buttons in the form tag
  • use variable declarations outside of return ( let return be for HTML tag and its better to use your logics outside of return ) make it easier to read

and I think your code can be like this:

import React, { useState } from 'react'

export default function App() {
  const [todos , set_todos] = useState([''])
  const submitTask = (e) =>{

    // Calling preventDefault() during any stage of event flow cancels the event,
    // meaning that any default action normally taken by the implementation
    // as a result of the event will not occur
    e.preventDefault(); 

    const { taskInput } = e.target; // get your input by name

    // assign input value to your state
    set_todos(oldState => [...oldState, taskInput.value ]) 
  }
  return (
    <>
      <h1>hello world</h1>
      <form onSubmit={submitTask}>
        <input name="taskInput" />
        <button type="submit">add todo</button>
      </form>

      <ul>
        {todos.map(todo =>(
          <li>{todo}</li>
        ))}
      </ul>

    </>
  )
}
Sign up to request clarification or add additional context in comments.

Comments

0

You should use set_todos like below:

set_todos([...todos, input]);

Because set_todos is a function. You can find the State Hook's usage in Introducing Hooks.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.