Home > Back-end >  data exchange between components react typescript
data exchange between components react typescript

Time:07-26

In general, the task is simple. I want to transfer data from state Child.tsx in the state of the parent component Parent.tsx I'm a little confused about it. Help me figure it out, please. At the time of rendering in the Child.tsx already has todos, at least 3 because I use localstorage. And they are not displayed in Parent.tsx


Parent.tsx

const [todosChild, setTodosChild] = useState<ITodo[]>([])

let getTodos = (todos: ITodo[]) => {
    setTodosChild(todos);
}
console.log(todosChild); // []

<TodosPage create={getTodos} />

Child.tsx

interface TodosPageProps {
    create(todos: ITodo[]): void;
}

export const TodosPage: React.FC<TodosPageProps> = ({ create }) => {

  const getTodos = (todos: ITodo[]) => {
     return create;
  }

  const [todos, setTodos] = useState<ITodo[]>([])

}

ITodo.ts

 export interface ITodo {
  title: string
  body: string
  id: number
  completed: boolean
 }

CodePudding user response:

it would be nice to see how u are calling getTodos in the child component, btw if you are just calling it once like getTodos(todos) it won't work since you are not really calling the function create:

const getTodos = (todos: ITodo[]) => {
  return create; // <-- Not called
}

So you will need to call the create function inside the getTodos one:

const getTodos = (todos: ITodo[]) => {
  return create(todos); // <-- Now its called
}
  • Related