F
F
fif2022-04-09 17:47:08
typescript
fif, 2022-04-09 17:47:08

How to pass a function to a child component?

Good afternoon, I need to pass a function to the child component, and in the child component call it so that it re-renders the parent component.

Method (what I called a function) to be passed:

async fetchData(link = 'https://rickandmortyapi.com/api/character', name = '') {
    link = `${link}/?name=${name}`;
    await fetch(link)
      .then((res) => res.json())
      .then((data) => {
        this.setState({ info: data.info, results: data.results });
      })
      .catch(() => {
        const errorMessage = 'Something went wrong, try again';
        this.setState({ errorMessage });
      });
  }


This is how I pass it to the child component: This is how I call the passed function in the child component:<Search fetchData={this.fetchData} />

submitInput() {
    this.props.fetchData('', this.state.val);
}


But I get an error: Expected arguments: 0, received: 2.

This type of props : 1. How to fix the error Expected arguments: 0, received: 2. 2. If I call this function in a child component, will it be called in the parent , or how to call it from a child? () => void


Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2022-04-09
@fif

Такой тип у пропсов: () => void
And this is the mistake. Correct the type to accept your two arguments. UPD: You will still swear at the type of the return value of the function. fetchData returns a promise, and you have void types. This is how it should work
fetchData: (link: string, name: string) => void;

fetchData: (link: string, name: string) => Promise<Response>;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question