Riya Kapuria
Riya Kapuria

Reputation: 9750

How to reload current page in ReactJS?

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);
    });
  }

Upvotes: 40

Views: 207947

Answers (6)

Abdulhakim
Abdulhakim

Reputation: 758

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.

Upvotes: 1

Ashwath M N
Ashwath M N

Reputation: 21

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

Upvotes: 2

Michael Jones
Michael Jones

Reputation: 2272

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}
    );
  }
}

Upvotes: 11

Sachitha Hirushan
Sachitha Hirushan

Reputation: 643

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

Upvotes: 0

Tiago Alves
Tiago Alves

Reputation: 2316

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;

Upvotes: 15

Nisal Edu
Nisal Edu

Reputation: 7591

use this might help

window.location.reload();

Upvotes: 79

Related Questions