0

I am trying to print out user related items only. So i am try to get items by requesting data to user id /api/items/:userid I am using redux store

my server side code is like this

router.get("/:userid",(req, res) => {
  // Item.find({ "owner.ownerName": `${req.params.userid}`})
  Item.find({ "owner.id": `${req.params.userid}`})
    .sort({
      date: -1,
    })
    .then((items) => res.json(items));
   console.log(req.user)
});

The problem is my front end request. I don't know how to get user id inside ITEMACTION.

import {
  GET_ITEMS,
  ADD_ITEM,
  DELETE_ITEM,
  ITEMS_LOADING,
  UPDATE_ITEM,
  SUBSTRACT_ITEM,
} from "../actions/types";
import { tokenConfig } from "../actions/authActions";
import { returnErrors } from "../actions/errorActions";
import Axios from "axios";

export const getItems = () => (dispatch) => {
  // will hit reducer
  dispatch(setItemsLoading());
  Axios.get("/api/items/")
    .then((res) =>
      dispatch({
        type: GET_ITEMS,
        payload: res.data,
      })
    )
    .catch((err) => {
      dispatch(returnErrors(err.response.data, err.response.status));
    });
};

I actually tried to get user id from the redux store.

import store from '../store';

and inside getItems

store.getState().auth.user._id

the problem is that when i console.log in getItems the user id is always return null except first time after login. But when i look in redux dev tool. The user id is available

Redux store state image

how can i get the userid

1 Answer 1

2

Hey you can get the getState as a second argument in the inner function along with the dispatch, using that you can access the updated state in an action. Fixed Code:

export const getItems = () => (dispatch, getState) => {
  // will hit reducer
  const userId = getState().auth.user._id;
  console.log(userId) // should output the updated data
  dispatch(setItemsLoading());
  Axios.get("/api/items/")
    .then((res) =>
      dispatch({
        type: GET_ITEMS,
        payload: res.data,
      })
    )
    .catch((err) => {
      dispatch(returnErrors(err.response.data, err.response.status));
    });
};

store.getState doesn't return updated state, in order to get the updated state using store.getState() you need to subscribe to the state change.

const unsubscribe = store.subscribe(() => {
    // logs the state data everytime an action is dispatched.
    console.log("from listener: ", store.getState());
})

Details here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.