1

I'm working on a MERN project and I need your support. Which is the best way to get data with a REST call providing an array?

I have an array of ID's and would like to take data using axios and the mongoose method "findById".

I'm sending the array as params from the component; dispatch the action fetchItinerariesId that call the function fetchItinerariesId(favItin_id) where favItin_id is the array of id's, and the reducer add the payload to my state favItineraries: [].

Here below the code:

REST api call:

const express = require("express");
const router = express.Router();
const itineraryModel = require("../../models/itineraryModel");

//! GET FAV ITINERARIES //----------------------------------------------

//* @route   GET api/itineraries/:itin_id
//* @desc    Get itineraries per fav itin id
//* @access  Public
router.get("/itineraries/:favItin_id", (req, res) => {
  let itineraryRequestedId = req.params.favItin_id;
  itineraryModel
    .findById(itineraryRequestedId)
    .then(itinerary => {
      res.send(itinerary);
    })
    .catch(err => console.log(err));
});

module.exports = router;

Redux Actions:

import {
  FETCH_ITINERARIES_ID_PENDING,
  FETCH_ITINERARIES_ID_SUCCESS
} from "./typesActions";

//! FETCH FAVORITES BY USER ID //-------------------------------------------------------------

export function fetchItinerariesIdPending() {
  return {
    type: FETCH_ITINERARIES_ID_PENDING
  };
}

export const fetchItinerariesId = favItin_id => dispatch => {
  console.log("inside action fetchItineraries per fav ID");
  console.log(favItin_id);

  dispatch(fetchItinerariesIdPending());
  axios
    .get("/api/profile/itineraries", { favItin_id: favItin_id })
    .then(res => {
      dispatch({
        type: FETCH_ITINERARIES_ID_SUCCESS,
        payload: res.data
      });
    });
};

Redux Reducer

  FETCH_ITINERARIES_ID_PENDING,
  FETCH_ITINERARIES_ID_SUCCESS
} from "../actions/typesActions";

const initialState = {
  pending: false,
  favItineraries: []
};

function profileReducer(state = initialState, action) {
  switch (action.type) {
    // GETS FAVORITES FROM ITINERARIES USING ITIN ID
    case FETCH_ITINERARIES_ID_PENDING:
      return {
        ...state,
        pending: true
      };

    case FETCH_ITINERARIES_ID_SUCCESS:
      return {
        ...state,
        pending: false,
        favItineraries: action.payload
      };

    default:
      return state;
  }
}

export default profileReducer;

React view component:

 /*----- MATERIAL UI -----*/
import Box from "@material-ui/core/Box";...

/*----- REACT/ROUTER/REDUX -----*/
import React, { Component, Fragment } from "react";
import { connect } from "react-redux"; // connect component to  redux store.

/*----- COMPONENTS/ACTIONS -----*/
import Navbar from "../components/Navbar";
import ItininerariesList from "../components/ItinerariesList";
import { loadUser } from "../store/actions/authActions";
import { fetchItinerariesId } from "../store/actions/profileActions";
import { fetchActivities } from "../store/actions/activitiesActions";

class Profile extends Component {
  componentDidMount() {
    this.props.loadUser();
    let favItin_id = this.props.favItin_id;
    this.props.fetchItinerariesId(favItin_id);
  }

  render() {
    const { favitineraries, activities } = this.props;

    return (
      <Fragment>
        <Container maxWidth="sm">
          <Typography component="div">
            <Box fontSize="h7.fontSize" textAlign="left" mb="3">
              Favorites MYtineraries:
            </Box>

            <ItininerariesList
            itineraries={favitineraries}
            activities={activities}
            />

          </Typography>
        </Container>

        <div className="navbar">
          <Navbar />
        </div>
      </Fragment>
    );
  }
}

const mapStateToProps = (state, ownProps) => {
  return {
    favItin_id: state.auth.user.favorites,
    favitineraries: state.profileRed.favItineraries,
    activities: state.activitiesRed.activities
  };
};

export default connect(mapStateToProps, {
  loadUser,
  fetchItinerariesId,
  fetchActivities
})(Profile);

Any suggestions or guidance would be greatly appreciated. Thank you in advance.

anthares
  • 85
  • 1
  • 5
  • you wrote a lot of code without good explaining for what you want to do all what you need is to send an array of object to mongoose and retrieve a list of objects?-by the way in js an array is an object as well- – youssef ali Dec 08 '19 at 17:34
  • 1
    here a way to find multiple ids https://stackoverflow.com/a/8304213/11252816 using $in – youssef ali Dec 08 '19 at 17:37
  • thank you youssef! the mongoose method $in solved my issue. – anthares Dec 09 '19 at 10:16

0 Answers0