Coder Social home page Coder Social logo

ledoux / redux-thunk-data Goto Github PK

View Code? Open in Web Editor NEW

This project forked from betagouv/redux-thunk-data

0.0 1.0 0.0 3.68 MB

A lib for fetching normalized data in a redux store through thunk

License: Mozilla Public License 2.0

JavaScript 89.00% Shell 11.00%

redux-thunk-data's Introduction

redux-thunk-data logo

A lib for fetching normalized data in a redux store through thunks.

Inspiration was taken from redux advices with async actions. A list of other frameworks like this could be found here. Also, see this post for a presentation based on the pass culture project.

CircleCI npm version

Basic Usage

You need to install a redux-thunk setup with the dataReducer from fetch-normalize-data. You can also use the requestsReducer to have a status state of the request :

import {
  applyMiddleware,
  combineReducers,
  createStore
} from 'redux'
import thunk from 'redux-thunk'
import { createDataReducer, createRequestsReducer } from 'redux-thunk-data'

const storeEnhancer = applyMiddleware(
  thunk.withExtraArgument({ rootUrl: "https://momarx.com" })
)
const rootReducer = combineReducers({
  data: createDataReducer({ foos: [] }),
  requests: createRequestsReducer()
})
const store = createStore(rootReducer, storeEnhancer)

Then you can request data from your api that will be stored in the state.data

react old school

import React, { PureComponent } from 'react'
import { requestData } from 'redux-thunk-data'


class Foos extends PureComponent {
  constructor () {
    super()
    this.state = { error: null }
  }

  handleFooClick = foo => () => {
    const { dispatch } = this.props
    dispatch(requestData({
      apiPath: '/foos',
      body: {
        isOkay: !foo.isOkay
      },
      method: 'PUT'
      handleFail: (state, action) =>
        this.setState({ error: action.payload.error })
    }))
  }

  componentDidMount () {
    const { dispatch } = this.props
    dispatch(requestData({
      apiPath: '/foos',
      handleFail: (state, action) =>
        this.setState({ error: action.payload.error })
    }))
  }

  render () {
    const { foos, isFoosPending } = this.props
    const { error } = this.state

    if (isFoosPending) {
      return 'Loading foos...'
    }

    if (error) {
      return error
    }

    return (
      <>
        {(foos || []).map(foo => (
          <button
            key={foo.id}
            onClick={this.handleFooClick(foo)}
            type="button"
          >
            {foo.isOkay}
          </button>
        ))}
      </>
    )
  }
}

const mapStateToProps = state => ({
  foos: state.data.foos,
  isFoosPending: (state.requests.foos || {}).isPending
})
export default connect(mapStateToProps)(Foos)

NOTE: We could also used a handleSuccess in the requestData api, in order to grab the action.data foos. In that case, code to be modified is:

constructor () {
  this.state = { error: null, foos: [] }
}

handleFooClick = foo => () => {
  const { dispatch } = this.props
  dispatch(requestData({
    apiPath: '/foos',
    body: {
      isOkay: !foo.isOkay
    },
    method: 'PUT'
    handleFail: (state, action) =>
      this.setState({ error: action.error })
    handleSuccess: (state, action) => {
      const { foos } = this.props
      const nextFoos = foos.map(foo => {
        if (foo.id === action.payload.datum.id) {
          return {...foo, action.payload.datum }
        }
        return foo
      })
      this.setState({ foos: nextFoos })
    },
  }))
}

componentDidMount () {
  const { dispatch } = this.props
  dispatch(requestData({
    apiPath: '/foos',
    handleFail: (state, action) => this.setState({ error: action.payload.error }),
    handleSuccess: (state, action) => this.setState({ foos: action.payload.data }),
    method:'GET'
  }))
}

render () {
  const { error, foos } = this.state
  ...
}

But if your rendered foos array should be coming from a memoizing merging (and potentially normalized) (and potentially selected from inter data filter conditions) state of foos, then syntax goes easier if you pick from the connected redux store lake of data.

react hooks school

import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { requestData } from 'redux-thunk-data'

const Foos = () => {
  const dispatch = useDispatch()

  const [error, setError] = useState(null)


  const foos = useSelector(state =>
    state.data.foos)

  const { isPending: isFoosPending } = useSelector(state =>
    state.requests.foos) || {}


  const handleFooClick = foo => () =>
    dispatch(requestData({
      apiPath: '/foos',
      body: { isOkay: !foo.isOkay },
      method: 'PUT'
      handleFail: (state, action) => setError(action.payload.error)
    }))


  useEffect(() =>
    dispatch(requestData({
      apiPath: '/foos',
      handleFail: (state, action) => setError(action.payload.error)
    })), [dispatch])


  if (isFoosPending) {
    return 'Loading foos...'
  }

  if (error) {
    return error
  }

  return (
    <>
      {(foos || []).map(foo => (
        <button
          key={foo.id}
          onClick={handleFooClick(foo)}
          type="button"
        >
          {foo.isOkay}
        </button>
      ))}
    </>
  )
}

redux-thunk-data's People

Contributors

akhilian avatar dependabot[bot] avatar faustinemassin avatar ledoux avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.