React typescript todolist giving error after modify state from child component

hello, i am building a todo list with react and typescript and i want to pass a value from a child element to the parent but i am getting the error

this is some of the code

type todosType = {
  id: number,
  isCompleted: boolean,
  item: string | number
}

function App() {
  const [todos, setTodos] = useState<todosType[]>([])
 return (
     <Tabs 
      setTodos={setTodos} 
      todos={todos} // "Type 'todosType[]' is not assignable to type '[{ id: number; isCompleted: boolean; item: string | number; }]'.  Target requires 1 element(s) but source may have fewer."
      deleteItem={deleteItem} 
      deleteAllCompleted={deleteAllCompleted} 
      onToggle={onToggle}
    />
)
}

and i have the following within Tabs component. although the error went away after setting the type of todos of TodoType to any, i want the correct way to do it.

type TodoType = {
  todos: [
    {
      id: number,
      isCompleted: boolean,
      item: string | number
    }
  ],
  deleteItem: (id: number) => void,
  onToggle: (id: number, status: boolean) => void
  deleteAllCompleted: () => void,
}

const Tabs = (props: TodoType) => {
// store the whole list
  const [newOrderItem, setNewOrderItem] = useState(props.todos)
 // below prevents the list from return to original state after drag and drop  
function handleDragEnd(result: DropResult) {
    if (!result.destination) {
      return;
    }
    
  if (result.destination.index === result.source.index && result.destination.droppableId === result.source.droppableId) {
      return;
    }

    const items = Array.from(newOrderItem)
    
    const [reorderedItem] = items.splice(result.source.index, 1)
    items.splice(result.destination.index, 0, reorderedItem)
    setNewOrderItem(items) //  argument of type '{ id: number; isCompleted: boolean; item: string | number; }[]' is not assignable to parameter of type 'SetStateAction<[{ id: number; isCompleted: boolean; item: string | number; }]>'.

return (
  // other components that use the state
)
  }
}

if you need more context, this is the repo

Try importing todosType into your Tabs component and declaring TodoType (fwiw, I do not recommend two nearly identical type names) to give the todos property the type todosType[] - just like how you declared the type of the todos state in your App component.

thanks a lot, your solution worked

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.