I need to change the state on a value and then re render a component. This component uses the new set value as part of the URL to retrieve same data.
I'm using React and TypeScript and I created two function components, one that changes the state and a child component that receives that new state as props.
Here is the code.
const Main :React.FC = ()=>{
const [status, setStatus] = useState('hold');
return(
<div >
<Row >
<Col >
<Nav >
<Nav.Item >
<Nav.Link href='#' onClick={()=>setStatus('active')} >Active </Nav.Link>
</Nav.Item>
<Nav.Item >
<Nav.Link href='#' onClick={()=>setStatus('hold')} >Idle </Nav.Link>
</Nav.Item>
<Nav.Item >
<Nav.Link href='#' onClick={()=>setStatus('close')}>Close </Nav.Link>
</Nav.Item>
</Nav>
</Col>
</Row>
<Row >
<Col >
<CardBody status={status} /> // CHILD COMPONENT
</Col>
</Row>
</div>
);
};
export default Main;
Any Ideas why the state does not change or why it might not re render?
EDIT
Adding the child component code:
const useFetch = (url:any) => {
const dataInfo = fetch(url)
.then( response => response.json());
return dataInfo;
}
export default ( status:any ) =>{
const [chats, setChats] = useState([]);
const estado= status.status;
useEffect( ()=>{
useFetch(`http://localhost:8901/api/chat/2/${estado}`).then(data => setChats(data.message));
},[]);
return (
<div>
{
chats.map((data:IProps, index:any)=>{
return (
<Accordion key={index}>
<Card >
<Card.Header >
<Accordion.Toggle as={Link} variant="link" eventKey="0">
<Card.Title> <span> {data.CLIENTNAME}</span> </Card.Title>
</Accordion.Toggle>
</Card.Header>
<Accordion.Collapse eventKey="0">
<Card.Body>
<Card.Title>{data.COMPANY}</Card.Title>
<Card.Text> {data.DESCRIPTION}</Card.Text>
</Card.Body>
</Accordion.Collapse>
</Card>
</Accordion>
)
})
}
</div>
);
}
This code runs fine the first time the page loads. I put a {status} on the parent component and I see that the status its changing. But I don't know why it's no re rendering the child component.
FINAL SOLUTION
adding STATUS to the useEffect() on the child component, final code is:
useEffect( ()=>{
useFetch(`http://localhost:8901/api/chat/2/${estado}`).then(data => setChats(data.message));
},
[status]); // added status here
Thanks for the answers!