Gettin 'null' while fetching data from api with React Context

Vahe

I'm trying to get a bunch of articles from API using axios and useContext hook in React, but getting 'null' as a response. This is the code from "State" file

import React, { useReducer } from "react";
import axios from "axios";
import ArticleContext from "./articleContext";
import articleReducer from "./articleReducer";
import { GET_ARTICLE } from "../types";

const ArticleState = (props) => {
  const initialState = {
    article: null,
  };

  const [state, dispatch] = useReducer(articleReducer, initialState);

  const getArticle = async (id) => {
    try {
      const res = await axios.get(`/articles/${id}`);
      dispatch({ type: GET_ARTICLE, payload: res.data });
    } catch (err) {
      console.log("errrrr");
    }
  };

  return (
    <ArticleContext.Provider
      value={{
        article: state.article,
        getArticle,
      }}
    >
      {props.children}
    </ArticleContext.Provider>
  );
};
export default ArticleState;

This is code from "Reducer"

import { GET_ARTICLE } from "../types";
// eslint-disable-next-line import/no-anonymous-default-export
export default (state, action) => {
  switch (action.type) {
    case GET_ARTICLE:
      return {
        ...state,
        article: action.payload,
      };
    default:
      return state;
  }
};

And finally code from the component, where i' trying to render data from the api call response and getting TypeError: article is null Am i missing something here? The main App component is also wrapped in <ArticleState></ArticleState>.

import React, { useEffect, useContext } from "react";
import ArticleContext from "../../context/article/articleContext";

const Article = () => {
  const articleContext = useContext(ArticleContext);
  const { article, getArticle } = articleContext;
  useEffect(() => {
    getArticle();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="article" key={article.id}>
      <h2 className="article__title">{article.Title}</h2>
      <p className="article__body">{article.preview}</p>
    </div>
  );
};

export default Article;
Luca Pizzini

You should check if the article has been set before displaying its data.
Add a condition to the component before rendering the article informations:

const Article = () => {
  const articleContext = useContext(ArticleContext);
  const { article, getArticle } = articleContext;

  useEffect(() => {
    getArticle();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  if (!article) {
      return <>Loading article...</>
  }

  return (
    <div className="article" key={article.id}>
      <h2 className="article__title">{article.Title}</h2>
      <p className="article__body">{article.preview}</p>
    </div>
  );
};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Getting an empty array in React while fetching the data from the api

Fetching data from api in react

Trouble while fetching data from API in Angular

Fetching data from api promise in react API

Fetching data from YouTube API with React Hooks

React Router Fetching data from API

Fetching data from api and passing it to state in React

react functional component is getting called 3 times while fetching data from api async way

Data's not displaying while fetching from API and using Flatlist in react native

Fetching API data with React

FIREBASE: getting null while fetching the data from database

null value is displaying while fetching data from database

Issues while Fetching API data in my react component

Error While Fetching Data From Google Analytics API from R

React generates infinite errors while fetching from api

Getting keyerror while fetching JSON data from API using python

How to run a closure in a completion closure while fetching data from an api?

Getting error autocomplete is not a function while fetching data from api?

Show a percentage indicator while fetching data from Rest API Flutter

Angular 2 Error while fetching data from api

Type error in http method while fetching data from api(php)

React: following DRY in React when fetching data from API

How to display "Fetching data" text to user while controller code is fetching data from API?

How to calculate Fetching Time while fetching data from any Api in Ajax

Fetching API data via React

Fetching data from nested array in API React Native

React.js: Fetching Data from API with Bearer Token

fetching POST data from API (node js, react)

React useEffect infinite loop fetching data from an api

TOP Ranking

HotTag

Archive