Refresh same page without reloading - Reactjs

Viewed 2998

How to refresh a page without reloading, by refreshing I want to invoke the componentDidMount() function and render the view again.

Below code works when redirecting to a different URL but will not work if we redirect to the same URL.

props.dispatch(push('/sameUrl'));

1 Answers

i had a similar problem, but i used redux in my project, after i got an element i just updated my page via 'redux-saga/effects' and 'connected-react-router' packages, i set an example (i cut most code and left only needed):

when i sent a request on creating a recipe:

import { takeLatest, all, call, put } from 'redux-saga/effects';
import { push } from 'connected-react-router';
import * as constants from './RecipesConstants';
import { recipeAPI } from './../../api/';

function* addRecipe(action) {
  try {
    const recipeResponse = yield call(recipeAPI.addRecipe, action.payload);


    yield put({
      type: constants.ADD_RECIPE_SUCCESS,
      payload: {
        ...recipeResponse.data
      }
    });

    yield put(push(`/recipes`)); // <----- here i update my page
  } catch (error) {
    yield put({
      type: constants.ADD_RECIPE_FAILED
    });

  }
}
export default function* recipesSaga() {
  yield all([
    takeLatest(constants.ADD_RECIPE, addRecipe)
  ])
}

hope, it'll help you

Related