skip to Main Content

is it possible to add data to redux state this method:

const dispath = useDispatch();

useEffect(() => {
    fetch(`https://newsapi.org/v2/top-headlines?country=${location.state}&apiKey=${apiKey}`)
      .then(res => res.json())
      .then(data => {
        setNewsAll(data)
        console.log(data)
        setLoadingNews(false)
        dispath(data.totalResults) // <= this line ! i know that it must be async 
      })
  }, [location])

i try another method, but it is possible somehow

2

Answers


  1. Yes, it is possible to add data from API to redux. What you can do is create some action that can handle storing the state in redux and can easily dispatch from your effect.

    const dispath = useDispatch();
    
    useEffect(() => {
        fetch(`https://newsapi.org/v2/top-headlines?country=${location.state}&apiKey=${apiKey}`)
          .then(res => res.json())
          .then(data => {
            setNewsAll(data)
            console.log(data)
            setLoadingNews(false)
            dispath(setData(data.totalResults)) // setData is an action that can set state inside redux
          })
      }, [location])
    
    Login or Signup to reply.
  2. Yes, it is possible to add data to the Redux state using the useDispatch hook.

    import { useDispatch } from 'react-redux';
    import { addData } from './actions';
    
    const dispath = useDispatch();
    
    useEffect(() => {
      fetch(`https://newsapi.org/v2/top-headlines?country=${location.state}&apiKey=${apiKey}`)
        .then(res => res.json())
        .then(data => {
          setNewsAll(data)
          console.log(data)
          setLoadingNews(false)
          dispath(addData(data.totalResults))
        })
    }, [location])
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search