pass async results from parent to child component react functional component

Viewed 471

I have a functional component that designed to search tasks and show in a task resultbox, the async Task data is set via useState hook and passed to the child component "TaskResultBox". The state is not changed and values are not rendered into the child component. I have verified the values retrieved from API using debug. but not re-rendering the data in the child component.

import React from 'react'
import {useState} from 'react'


function SearchTask({onAddTask}) {
    const [searchInputValue, setSearchInputValue] = useState('');
    const [tasks, setTasks] = useState('');
 
    const getTasks = () => {
        return tasks;
    };
    const onSearchInputValueChange = (e) => {
        setSearchInputValue(e.target.value);
    };
    const onSearch = async(e) => {
        const theRequestOpts = {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ searchString: searchInputValue })
        };
        const response = await fetch('/api/searchTasks', theRequestOpts);
        const data = await response.json();
        setTasks(data);
    };
    return (
        <InputBox onSearchInputValueChange={onSearchInputValueChange}/>
        <Button title="Search Tasks:" onClick={onSearch}/>
        <TaskResultBox taskResults={getTasks}/>
    )
}

export default SearchTask

// TaskTesultBox.js

import React from 'react'
function TaskResultBox({taskResults}) {
    return (
        <div>
            <h1>Task Result:</h1>
            <textarea value={taskResults}/>
        </div>
    )
}

export default TaskResultBox
1 Answers

getTasks is a function that returns a tasks object, so to get the return variable, you would need to invoke it

So change to:

<TaskResultBox taskResults={getTasks()}/>  //<-- Invoke it

But I wonder why do you need a function just to return that variable but not put it directly to the props?

Like so:

<TaskResultBox taskResults={tasks}/>
Related