3

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
3
  • What is in your TaskResultBox, would you please paste it here? Commented Sep 10, 2021 at 4:04
  • I've made an answer, see if it helps Commented Sep 10, 2021 at 4:12
  • You may find this blog about reactive programming with react interesting Commented Sep 10, 2021 at 14:49

1 Answer 1

3

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}/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.