Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

IO Monad in React App #25

Open
MalQaniss opened this issue Apr 22, 2022 · 0 comments
Open

IO Monad in React App #25

MalQaniss opened this issue Apr 22, 2022 · 0 comments

Comments

@MalQaniss
Copy link

Hi Kyle, I am trying to use IO monad in React app(I don't know how much you are familiar with it), and I thought of using it as custom hook for every fetching side-effect needed in component. This is what I came up with so far:

import {useEffect, useState} from "react";
import {IO} from 'monio'

const useIO = ({sideEffectFunction, args}, dependencies = []) => {

    const [data, setData] = useState(null)


    function* main() {
        try {
            const returnVal = yield sideEffectFunction(...args)
            setData(returnVal)
        }catch (err){
            setData(err)
        }
    }

    useEffect(() => {
        IO.do(main).run()
    }, dependencies)


    return data

}

export default useIO;

And I can use it in some component to fetch some data like this:

import { isNotNil, logIf} from "./ContinentsSectionHelper";
import useIO from "../../hooks/useIO";
import {IO} from "monio";
import {chain, map, pipe, prop} from "ramda";

//Helpers
const sendRequestForContinent = continent => sendGetRequest(`https://corona.lmao.ninja/v3/covid-19/continents/${continent}?strict=true`)
const sendGetRequest = url => IO(() => fetch(url))
const checkResponse = response => response.ok? IO.of(response) : IO(() => {throw "Oops something is wrong with response"})
const getResponseJson = response => IO(() => response.json())

const fetchCountriesOfContinent = pipe(
    sendRequestForContinent, // send request
    chain(checkResponse), // check if response is OK
    chain(getResponseJson), // convert response to JSON
    map(prop('countries')), //get country property
)

//Component
const ContinentsSection = () => {

    const data = useIO({sideEffectFunction: fetchCountriesOfContinent, args:['europe']})

    logIf(data)(isNotNil)


    return (
        <section>
            <ContinentGraph />
        </section>
    )

}

export default ContinentsSection;

Would you say that this example is one possible solution to using monio in react, and would you implement it in some other way?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant