Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I default category through api

I have written a project which receives data through an api. Clicking on each button displays corresponding news. For example, when you press the sports button, sports news comes. However, I want the All category to be active when the page is first opened. In other words, those news should have arrived without pressing the all button. How can I do this?

Not – The function inside useffect returns every time it renders and it doesn’t work for me. For example, when you refresh the page while reading sports news, all news comes

import React, { useEffect, useState } from "react";
import SpinnerLoad from './components/SpinnerLoad'
import NewsItem from "./components/NewsItem";
import Category from "./components/data/Category"
const App = () => {

  const [state, setState] = useState([]);
  const [loading, setLoading] = useState(false)


  const fetchValue = (category) => {
    fetch(`https://inshorts-api.herokuapp.com/news?category=${category}`)
      .then(res => res.json())
      .then(res => {
        setState(res.data)
        setLoading(true)
      })
      .catch((error) => console.log(error))
      setLoading(false);
  };

  const CategoryButton = ({ category }) => (
    <button onClick={() => fetchValue(category)} style={{ textTransform: 'capitalize' }}>{category}</button>
  );

  useEffect(() => {
    fetchValue('all')
  }, [])

  return (
    <>

      <div className="header-bg">
        <h1 className="mb-3">News</h1>
        <div className="btns ">
          {Category.map((value, index) => {
            return <CategoryButton category={value} key={index} />;
          })}
        </div>
      </div>

      <div className="news">
        <div className="container">
          <div className="row">
            { 
            !loading 
            ? <SpinnerLoad/>
             :
            state.map((data,index) => {
              return (
                <NewsItem
                  imageUrl={data.imageUrl}
                  author={data.author}
                  title={data.title}
                  content={data.content}
                  date={data.date}
                  key={data.id}
                />
              );
            })
            }
          </div>
        </div>
      </div>
    </>
  );
};
export default App;
import React from 'react'
import clock from "../components/assets/img/Clock.svg"
import user from "../components/assets/img/User.svg"
const NewsItem = (props) => {

    const {imageUrl, title, content, date, author} = props

    return (
        <div class="col-lg-4 col-md-6 col-12 p-2">
            <div className="newsItem">
                <img src={imageUrl} alt=''/>
                <div className="itemBody">
                    <p className='title'>{title}</p>
                    <div className="line"></div>
                    <p className='content'>{content}</p>
                    <div className="itemfooter">
                        <h6><img src={clock} alt='clock'/>{date}</h6>
                        <h6><img src={user} alt='user'/>{author}</h6>
                    </div>
                </div>

            </div>
        </div>
    )
}

export default NewsItem

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In react, if you refresh the app , the state values will reinitialise.

From your question , it seems like you want to store the category value and even after refresh , you want to persist the category value..

For that you can store category value in local or sessionStorage..

 const fetchValue = (category) => {
  localStorage.setItem("category", category);
  // your code
 }

 // in useEffect , you can check for the category value in the local Storage

useEffect(() => {
// check value in localStorage, if does not exist use "all" as default value
let categoryValue = localStorage.getItem("category") || "all" ;
fetchValue(categoryValue)
},[]);
 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading