I am making 2 react components (PlayerSearch for sumbitting a form containing target player's name, and PlayerAPI for fetching request). I want it to re-render PlayerAPI everytime I hit the submit button OR everytime the submitted data is updated. So my code looks like this: In PlayerSearch:
export function PlayerSearch() {
const [formData, setFormData] = useState({ APIkey: "", name: "" });
const [submittedData, setsubmittedData] = useState({ submittedAPIkey:"", submittedname:"" });
const onChange = (event) => {
setFormData({ ...formData, [event.target.name]: event.target.value });
};
function handlesubmit(e) {
e.preventDefault();
setsubmittedData({ ...submittedData, submittedAPIkey: formData.APIkey, submittedname: formData.name });
}
return <div className='player'>
<div className='inputfield'>
<form onSubmit={handlesubmit} method='GET' autoComplete="off">
<div>
<label htmlFor="APIkey">Your API key:</label>
<input placeholder='Your API key' onFocus={(e)=>{e.target.placeholder=''}} type="text" id="APIkey" name="APIkey" value={formData.APIkey} onChange={onChange}/>
</div>
<div>
<label htmlFor="name">Player name:</label>
<input placeholder='Player name' onFocus={(e)=>{e.target.placeholder=''}} type="text" id="name" name="name" value={formData.name} onChange={onChange}/>
</div>
<div>
<button type='submit'>Submit</button>
</div>
</form>
</div>
<div id='result'>
//This is where I render the PlayerAPI
{(submittedData.submittedAPIkey !== "" && submittedData.submittedname !== "") && <PlayerAPI APIkey={submittedData.submittedAPIkey} name={submittedData.submittedname} />}
</div>
</div>
}
Edit: I've found out that the form submit is not the problem. The problem is in the PlayerAPI and I fixed it.
The PlayerAPI before:
export function PlayerAPI(props) {
const [data, setdata] = useState({ accountId: ''});
const getPlayerID = async () => {
//some API fetching...
}
useEffect(()=>{
getPlayerID();
},[]);
return <div>
<div className='SearchResult'>
hello {JSON.stringify(data)}
</div>
</div>;
}
The PlayerAPI now:
import { useEffect, useState } from "react";
export function PlayerAPI(props) {
const [data, setdata] = useState({ accountId: ''});
const getPlayerID = async () => {
//some API fetching...
}
useEffect(()=>{
getPlayerID();
},[props.name, props.APIkey]);
return <div>
<div className='SearchResult'>
hello {JSON.stringify(data)}
</div>
</div>;
}