Muhd Iqbal
Muhd Iqbal

Reputation: 29

Click onClick twice in <Link> to update state

I'm trying to update my state by triggering the onClick event in my <Link>, but only after I click it twice then the output appears in my console, I have tried reading other question similar to this in stackoverflow but still could not find the solution, can anybody tell me what I did worng? Your help would be really great

import React,{useState} from 'react';
import { BrowserRouter as Router, Link } from 'react-router-dom';

const [search, setSearch] = useState("");
const [keyword, setKeyword] = useState("");

const handleChange = (e) =>{
    setSearch(e.target.value);
    console.log(search);
};

const handleClick = () => {
    setKeyword(search);
    setSearch('');
    console.log(keyword);
};

return(
    <div>
        <input onChange={handleChange} value={search} placeholder="Search songs, artist, albums"/>

        <Link onClick = {handleClick} to={`/songlist/${keyword}`}>Search</Link>
    </div> 
)

Upvotes: 0

Views: 345

Answers (3)

Vahid Alimohamadi
Vahid Alimohamadi

Reputation: 5858

JS is async, so you need to handle effects using useEffect hook.

e.g. :

const [search, setSearch] = useState(null);
const [keyword, setKeyword] = useState(null);

const handleClick = () => {
  setKeyword(search);
  //setSearch('');
  //console.log(keyword);
};

React.useEffect(()=>{
  if (keyword) {
    console.log(keyword);
    setSearch(null);
  }
},[keyword]);

Upvotes: 1

Claudio Antonius
Claudio Antonius

Reputation: 21

can you try this, change

<Link onClick = {handleClick} to={`/songlist/${keyword}`}>Search</Link>

to

<Link to={`/songlist/${search}`}>Search</Link>

Upvotes: 0

RaeperFR
RaeperFR

Reputation: 27

The thing you need to understand is : When you click, you add an event, and it's event is linked on your component and your props.

So you need to preventDefault to tell your event/props/component to act normally. Keep your actually code, but add e.preventDefault() at the begin of each event :)

Example :

const handleChange = (e) =>{
    e.preventDefault();
    setSearch(e.target.value);
    console.log(search);
};

Upvotes: 1

Related Questions