Need some help with async functions

Hey everyone I have an async handle change function that tracks my radio buttons’ values then sends it to local storage. The problem Im having is that when I set the state of the state called difficulty it is not getting the data cuz its not asynchronous. So to fix this I changed the function to async but I am still getting the same results of difficulty changing after the handle change function not while the function is running. Any ideas how to solve this?
.

const {deleteTask, editTask, tasks} = useContext(TaskContext);
    const [difficulty, setDifficulty] = useState('low');

    const handleChange=async(e)=>{
        const asyncSetDifficulty = await setDifficulty(e.target.value);
        console.log("async",difficulty)
        editTask(task.title,asyncSetDifficulty,task.id);
        
    }

    console.log("a",difficulty)
    console.log("b",tasks)

    return(
        <div>
            <h3>{task.title}</h3>
            <form onChange={handleChange} >
                <input  type="radio" value="low" name="difficulty"/>Low
                <input  type="radio" value="medium" name="difficulty"/>Medium
                <input  type="radio" value="high" name="difficulty"/>High
            </form>
1 Like

Hello there,

I am not aware of the function useState returns returning anything itself. That is,

const asyncSetDifficulty = await setDifficulty(e.target.value);

I am surprised, if asyncSetDifficulty is not undefined.


I am not too sure what you are doing, but I would have thought something like this would be more common:

const [difficulty, setDifficulty] = useState('low');
useEffect(() => {
  editTask(task.title, difficulty, task.id)
}, [difficulty])
const handleChange=(e)=>{
    setDifficulty(e.target.value);
}

This way, then difficulty changes, the useEffect callback is invoked.

Hope this helps

1 Like