React TypeError: "x" is not a function

Viewed 2837

I called a function setTodos from the parent in my child components, but this returns the following error:

setTodos is not a function

Can you explain me why this happened, thanks a lot. Here is my code:

import React, { useState } from 'react';
import './App.css';
import Form from './components/Form';
import TodoList from './components/TodoList';

function App() {
   const [inputText, setInputText] = useState("");
   const [todos, setTodos] = useState([]);
   return (
      <div className="App">
         <header>
            <h1>Phuc's Todo list</h1>
         </header>
         <Form inputText={inputText} todos={todos} setTodos={setTodos}/>
         <TodoList/>
      </div>
   );
}

export default App;
import React from 'react';

const Form = ({inputText, setInputText, todos, setToDos}) => {
   const inputTextHandler = (e) => {
      setInputText(e.target.value);
   }
   const submitTodoHandler = (e) => {
      e.preventDefault();
      setToDos([
         ...todos,
         {text: inputText, completed: false, id: Math.randowm()*1000}
      ])
   }
   return (
      ...
   )
}
3 Answers

There is a typo in your code while calling the setTodos in child component

It should be setTodos in child instead of setToDos. You have capital D, It should be small d.

As Javascript is case sensitve langauge. So you have to use the exact term.

setTodos([//here your code]);

In your parent component, setTodos need to be a callback if you want to do it that way.

Try with setTodos={(newTodos) => setTodos(newTodos)} inside your of parent component.

You are passing the setTodos as a prop into your child component. So, probably you are calling there setToDos instead setTodos.

Related