0
votes

I managed to get data from a my json.server into the desired component using the React-Redux methods, useSelector and useDispatch along with React's useEffect method.

What's confusing me is that even though the content of the array is there, the key for it is showing as undefined.

The console output: Screenshot of console log

The component:

import React, { useEffect } from 'react';
import SetlistItem from './SetlistItem';
import { fetchSongs } from '../../actions/index'

import { useSelector, useDispatch } from 'react-redux';

const SetlistContainer = () => {
  const songs = useSelector(state => state);

  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(fetchSongs())
  }, [dispatch])

  console.log(songs)

  return <div><SetlistItem /></div>
}

export default SetlistContainer;

The action:

export const fetchSongs = () => async dispatch => {
  const response = await songEntries.get("/songEntries");

  dispatch({ type: FETCH_SONGS, payload: response.data });
}

The reducer:

export default (state = {}, action) => {
  switch (action.type) {
    case FETCH_SONGS:
      return { ...state, [action.payload.id]: action.payload };
    case CREATE_SONG:
      return { ...state, [action.payload.id]: action.payload };
    default:
      return state;
  }
}

The db.json:

{
  "songEntries": [
    {
      "id": 1,
      "songTitle": "This is a song title",
      "notes": "These are some notes"
    }
  ]
}
1
How the fetchSongs looks like?norbitrial
The reducer would also be helpfulBrian Thompson
Thanks... I've added those to the op.Mark Williams
It seem that results songEntries.get("/songEntries") does not have id property, instead, it contain array of objects with these properties.Kyr

1 Answers

0
votes

I found the problem.

I needed to use the mapKeys method from the lodash library.

I should have made it clearer in the op that I'm trying to fetch an array of records, even though rather unhelpfully, I've only placed one element in the placeholder array.

Anyway the code is now this...

export default (state = {}, action) => {
  switch (action.type) {
    case FETCH_SONGS:
      return { ...state, ..._.mapKeys(action.payload, 'id') };
    case CREATE_SONG:
      return { ...state, [action.payload.id]: action.payload };
    default:
      return state;
  }
}