i’m creating a comment box with frontend in react; the main component has another one nested and one child.
Here’s the main component:
import { useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { fetchComments } from '../actions/commentsActions'
import { selectComments } from '../selectors/commentsSelectors'
import Message from '../components/Message'
import { Col, Container } from 'react-bootstrap'
import Blogs2 from './Blogs2'
const Blogs = () => {
const dispatch = useDispatch()
const comments = useSelector(selectComments)
useEffect(() => {
dispatch(fetchComments())
}, [dispatch])
return (
<Container>
<Blogs2 />
{comments.map(comment=>(
<Col key={comment._id} sm={12} md={6} lg={4} xk={3} >
<Message comment={comment} />
</Col>))}
</Container>
)
}
export default Blogs
This is the nested component where i wrote the post request:
import React, { useState} from 'react'
import axios from 'axios'
import { Row } from 'react-bootstrap'
const Blogs2 = () => {
const [author, setAuthor] = useState('');
const [text, setText] = useState('');
const [comments, setComments] = useState([]);
const client = axios.create({
baseURL: "http://localhost:5000/comments/"
});
const addPosts = (author, text) => {
client
.post('', {
author: author,
text: text,
})
.then((response) => {
setComments([response.data, ...comments]);
});
setAuthor('');
setText('');
};
const handleSubmit = (e) => {
e.preventDefault();
addPosts(author, text);
};
return (
<Row>
<form onSubmit={handleSubmit}>
<input value={author} onChange={(e)=>setAuthor(e.target.value)} />
<input value={text} onChange={(e)=>setText(e.target.value)} />
<input type='submit' />
</form>
</Row>
)
}
export default Blogs2
Here’s the child component:
import React from 'react'
import { Row } from 'react-bootstrap'
import './css/Message.css'
const Message = ({comment}) => {
return (
<Row id='commenti'>
<h1>{comment.author}</h1>
<h1>{comment.text}</h1>
</Row>
)
}
export default Message
All works until that when the form is submitted and the post request done, i need my page to be reloaded in order to my get request be done after that.
Any advice?
2
Answers
If you want your to reload your page completely you can use
window.location.reload();
or
you can create a function refreshData Blogs component to fetch the comments and pass it as props to Blogs2 component, call refreshData from Blogs2 .
My Suggestion Is Just Call Your Get API After Successful POST Request
if you do window.location.reload it is reload whole page and after that you will be redirected to top