0

I'm trying to find a way to convert this code to class based component:

import React, {useEffect} from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { bindActionCreators } from 'redux'
import { addComments } from './state/actions/commentActions'


export default function App() {

    const state = useSelector((state) => state)
    const dispatch = useDispatch()

    const {commentData} = state

    console.log(commentData);

    const add = bindActionCreators(addComments, dispatch)


    useEffect(() =>{
        async function fetchData(){
            const data = await fetch('https://jsonplaceholder.typicode.com/comments?_limit=10').then(data => data.json())
            add(data)
        }

        fetchData()

    }, [])

    const carr = commentData.map(data => <h1>{data.body}</h1>)

    return (
        <div>
            {carr}
        </div>
    )
}

I wasn't using class based components when I first learnt redux so I don't know how to replace those hooks other than connect HOC, unfortunately I've put in the position where I can't use them. So how do you implement bindActionCreators on a class based components?

Melly
  • 675
  • 8
  • 24

1 Answers1

0

My first question is, why are you trying to convert a function component into a class component? Normally, people are trying to convert classes into functions :)

That said, to specifically answer your question: you don't have to call bindActionCreators yourself - connect will do it internally:

https://react-redux.js.org/using-react-redux/connect-mapdispatch#defining-mapdispatchtoprops-as-an-object

import { increment, decrement, reset } from './counterActions'

const actionCreators = {
  increment,
  decrement,
  reset,
}

export default connect(mapState, actionCreators)(Counter)
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • I will probably make a separate question about the reason, it's HOC related stuff, I don't want to bring it up because it will be two different question. I'm trying to see if I can do this first – Melly Jul 07 '21 at 23:03