Skip to content

Instantly share code, notes, and snippets.

@tarasowski
Last active March 29, 2019 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarasowski/e330149b758ff2468c846b6af22661cb to your computer and use it in GitHub Desktop.
Save tarasowski/e330149b758ff2468c846b6af22661cb to your computer and use it in GitHub Desktop.
React Hooks
import React, { useState, useEffect } from 'react';
import * as S from 'sanctuary'
import {ul, li, a, div, input, button, pre, p} from 'react-hyperscript-helpers'
import axios from 'axios'
import $ from 'sanctuary-def'
const getResult = data =>
S.fromMaybe ([]) (S.gets (S.is ($.Array ($.Object))) (["data", "hits"]) (data))
const value = e =>
S.fromMaybe ("no value") (S.gets (S.is ($.String)) (["target", "value"]) (e))
const update = ([state, setState]) => ([state, setState,
useEffect(() => {
setState({...state, isLoading: true})
axios.get(state.url)
.then(res => setState({...state, hits: getResult(res), isLoading: false}))
.catch(_ => setState({...state, isLoading: false, isError: true, errorMessage: "Something went wrong. Please contant the website owner"}))
return
}
, [state.url])])
const view = ([state, setState]) =>
S.prop ("isLoading") (state)
? div({}, p({}, "Loading ....."))
: S.prop ("isError") (state)
? div({}, [
p({}, S.concat ("Error Message: ") (S.prop ("errorMessage") (state))),
input({
type: "text",
onChange: e => setState({...state, query: value(e)})
}),
button({
type: "button",
onClick: () => setState({...state, url: `http://hn.algolia.com/api/v1/search?query=${state.query}`})
}, "Search"),
])
:
div({}, [
input({
type: "text",
onChange: e => setState({...state, query: value(e)})
}),
button({
type: "button",
onClick: () => setState({...state, url: `http://hn.algolia.com/api/v1/search?query=${state.query}`})
}, "Search"),
ul({},
S.maybe
([li({key: 'nokey'}, 'no data')])
(S.map (i => li({key: i.created_at_i + i.author}, [a({href: i.url, target: "_blank"}, i.title)])))
(S.get (S.is ($.Array ($.Unknown))) ('hits') (state)),
),
])
const App = () =>
S.compose (view) (update) (useState({
hits: [],
query: "redux",
search: "react",
url: "http://hn.algolia.com/api/v1/search?query=redux",
isLoading: false,
isError: false,
errorMessage: "",
}))
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment