38

How to reload current page in ReactJS? in case of javascript we can write window.location.reload(); How to do the same in Reactjs? I'm able to add new data by UI. But without refreshing, I'm not able to see the list. I want it so that whenever I'm adding some data, it refreshes by itself.

onAddBucket() {
    let self = this;
    let getToken = localStorage.getItem('myToken');
    var apiBaseUrl = "...";
    let input = {
      "name" :  this.state.fields["bucket_name"]
    }
    axios.defaults.headers.common['Authorization'] = getToken;
    axios.post(apiBaseUrl+'...',input)
    .then(function (response) {

      if(response.data.status == 200){
      let result =  self.state.buckets.concat(response.data.buckets)
      }else{
        alert(response.data.message);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }
Bradley A.
  • 73
  • 1
  • 8
Riya Kapuria
  • 9,170
  • 7
  • 18
  • 32

6 Answers6

76

use this might help

window.location.reload();
Nisal Edu
  • 7,237
  • 4
  • 28
  • 34
  • 3
    this works when you already on that location which you want... It's important to notice what is your current path location – Nastro Nov 01 '18 at 19:48
  • 2
    This reload the page, but then the styles don't load! I'm working with a single page app, if that means anything. – Sam Sverko Oct 02 '19 at 20:42
14

You can use window.location.reload(); in your componentDidMount() lifecycle method. If you are using react-router, it has a refresh method to do that.

Edit: If you want to do that after a data update, you might be looking to a re-render not a reload and you can do that by using this.setState(). Here is a basic example of it to fire a re-render after data is fetched.

import React from 'react'

const ROOT_URL = 'https://jsonplaceholder.typicode.com';
const url = `${ROOT_URL}/users`;

class MyComponent extends React.Component {
    state = {
        users: null
    }
    componentDidMount() {
        fetch(url)
            .then(response => response.json())
            .then(users => this.setState({users: users}));
    }
    render() {
        const {users} = this.state;
        if (users) {
            return (
                <ul>
                    {users.map(user => <li>{user.name}</li>)}
                </ul>
            )
        } else {
            return (<h1>Loading ...</h1>)
        }
    }
}

export default MyComponent;
Tiago Alves
  • 2,290
  • 13
  • 32
  • You say a re-render may be preferable to a reload after a data update. If the server data has changed a reload will ensure that you are displaying the current server data, as opposed to a re-render which will just update the front end, and may not display the same data as the server. Or am I misunderstanding something? (I guess it depends how confident you are that thw server data will be as you expect without a reload). – wobbily_col Jul 29 '19 at 07:46
  • If the data has changed in the server and you want to show it, the frontend should have a method to get that data like WebSockets or polling and trigger a re-render when this new data is fetched. – Tiago Alves Aug 01 '19 at 14:19
  • You say "..and trigger a re-render when this new data is fetched." Isn't a reload basically fetching the data then re-rendering? – wobbily_col Aug 02 '19 at 07:35
  • 1
    A re-render doesn't trigger a page reload. They are different concepts. A reload refreshes the whole page, fetching all the data again. Re-render updates only the necessary. – Tiago Alves Sep 02 '19 at 23:35
  • I would like to trigger a re-render, but `this.setState()` says that `this` is undefined because I need to trigger this re-render inside of a callback. Got any ideas? – Aaron Franke Dec 18 '20 at 03:02
11

Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it in a `componentDidMount()' function in a React class.

For your edit, you may want to try something like this:

class Component extends React.Component {
  constructor(props) {
    super(props);
    this.onAddBucket = this.onAddBucket.bind(this);
  }
  componentWillMount() {
    this.setState({
      buckets: {},
    })
  }
  componentDidMount() {
    this.onAddBucket();
  }
  onAddBucket() {
    let self = this;
    let getToken = localStorage.getItem('myToken');
    var apiBaseUrl = "...";
    let input = {
      "name" :  this.state.fields["bucket_name"]
    }
    axios.defaults.headers.common['Authorization'] = getToken;
    axios.post(apiBaseUrl+'...',input)
    .then(function (response) {
      if (response.data.status == 200) {
        this.setState({
          buckets: this.state.buckets.concat(response.data.buckets),
        });
      } else {
        alert(response.data.message);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }
  render() {
    return (
      {this.state.bucket}
    );
  }
}
Bradley A.
  • 73
  • 1
  • 8
Michael Jones
  • 2,222
  • 18
  • 32
  • Hello @RiyaKapuria, so maybe what you would want to do is call the api necessary to grab the data and then once it has been loaded in, use a callback function that executes the page refresh. – Michael Jones Nov 09 '17 at 12:41
  • 1
    Also, Tiago above makes a very solid point. You may just be looking for a re-render, which, in that case, React handles very well. – Michael Jones Nov 09 '17 at 12:41
  • I want the concatenation for the data – Riya Kapuria Nov 09 '17 at 13:02
  • I am sorry, I am not completely sure what you mean. Please elaborate a little bit more – Michael Jones Nov 09 '17 at 13:07
  • onAddBucket() { let self = this; let getToken = localStorage.getItem('myToken'); var apiBaseUrl = "..."; let input = { "name" : this.state.fields["bucket_name"] } axios.defaults.headers.common['Authorization'] = getToken; axios.post(apiBaseUrl+'...',input) .then(function (response) { if(response.data.status == 200){ let result = self.state.buckets.concat(response.data.buckets) }else{ alert(response.data.message); } }) .catch(function (error) { console.log(error); }); } – Riya Kapuria Nov 09 '17 at 13:10
  • this is how I'm trying to do. But I'm unable to update the data without page refresh – Riya Kapuria Nov 09 '17 at 13:11
  • Hey @RiyaKapuria, please update your question with the formatted code example so we can try to help you. – Tiago Alves Nov 09 '17 at 13:14
  • When looking at your code it looks like you are trying to set the state of the React component with `this.state`. Instead, try to do something along the lines of `this.setState({ buckets: this.state.buckets.concat(response.data.buckets) })`. Also, that in turn will trigger a component re-render. – Michael Jones Nov 09 '17 at 13:15
  • 1
    Also, did you look at the example in my answer? I think it addressed your problem very well. you have to use `this.seState()` method. – Tiago Alves Nov 09 '17 at 13:16
  • For the update, it will grab the data once the component is mounted and update the component state. Then, the data will be available in the render as `this.state.bucket`. – Michael Jones Nov 09 '17 at 13:27
1

You can use useNavigate and navigate to the same url you are on. For example, instead of window.location.reload(), you can say navigate("/...your current url....")

window.location.reload() is not the best option everytime. It works on localhost, but for example on when you deploy it to the internet by using services such as "Netlify", it can can cause "not found url" error

Creating some extra state and tracking them for re-rendering your page might unnecessarily complicate your code.

And using useEffect() to re-render your page, again, will unnecesarily complicate your code.

Abdulhakim
  • 620
  • 8
  • 11
0

This is my code .This works for me

componentDidMount(){
        axios.get('http://localhost:5000/supplier').then(
            response => {
                console.log(response)
                this.setState({suppliers:response.data.data})
            }
        )
        .catch(error => {
            console.log(error)
        })
        
    }

componentDidUpdate(){
        this.componentDidMount();
}

window.location.reload(); I think this thing is not good for react js

0

use useHistory method in react import {useHistory} from 'react-router-dom' const history = useHistory()

history.go(0) // it will refresh particullar page

or use useEffect method

const [data, setData] = useState([])

useEffect(()=>{ setData(reponseApidata)},[data])

//in useEffect dependcy you mention particullar state for you store reposnse data