Home > front end >  React: Why is my state component not rendering?
React: Why is my state component not rendering?

Time:02-03

I am using context and reducer API for state management and logic. The below code returns context provider, which is called in App.js. Why isn't the component rendering?

SingerState.js

import React, { useReducer } from "react";

import SingerContext from "./singerContext";
import SingerReducer from "./singerReducer";

import { GET_SINGER, SET_LOADING } from "../types";

const SingerState = (props) => {
  console.log('foo')
  const initialState = {
    name: null,
    songs: null,
    loading: false,
  };
  const [state, dispatch] = useReducer(SingerReducer, initialState);

  const getSinger = () => {
    dispatch({
      type: GET_SINGER,
      payload: {
        name: "jb",
        songs: ["song1", "song2"],
      },
    });
  };
  const setLoading = () => {
    dispatch({
      type: SET_LOADING,
    });
  };
  return (
    <SingerContext.Provider
      value={{
        name: state.name,
        songs: state.songs,
        loading: state.loading,
        getSinger,
        setLoading,
      }}
    >
      {props.childer}
    </SingerContext.Provider>
  );
};

export default SingerState;

The entire code is in here: https://codesandbox.io/s/heuristic-shockley-9u2xb?file=/src/App.js:0-411

App.js

import "./App.css";
// import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
import SingerState from "./context/singer/singerState";

import Navbar from "./components/Navbar";
import Singer from "./components/singer/Singer";

export default function App() {
  return (
    <div className='App'>
      <Navbar />
      <SingerState>
        <Singer />
      </SingerState>
    </div>
  );
}

singerReducer.js

import { GET_SINGER, SET_LOADING } from "../types";

const reducer = (state, action) => {
  switch (action.types) {
    case GET_SINGER:
      return {
        ...state,
        name: action.payload.name,
        song: action.payload.song,
        loading: false,
      };
    case SET_LOADING:
      return {
        ...state,
        loading: true,
      };
    default:
      return state;
  }
};
export default reducer;

singerContext.js

import { createContext } from "react";
const singerContext = createContext();
export default singerContext;

CodePudding user response:

It should be {props.children} not {props.childer} in SingerState.js. I made this correction inside your Sandbox and it is working. To make sure, I changed initialState to this :

 const initialState = {
    name: "It's me",
    songs: null,
    loading: false,
  };

CodePudding user response:

You have 2 typos in your code: 1- It should be {props.children} not {props.childer} in SingerState.js. (Thanks to yousoumar)

And in SingerReducer.js. Instead of :

switch (action.types) {
    case GET_SINGER:

use action.type because types is not defined

Be carefully with typos!!!

  •  Tags:  
  • Related