use fetch hook react code example

Example 1: fetch api react

// This is what I've been using, pretty straight forward
// It passes the JSON to the children as props
// Of course, you fetch what you will

import React, { Component, Fragment } from 'react';

export class FetchJsonController extends Component
{
	constructor(props) {
		super(props);
		this.state = {
			data: null,
		};
	}

	componentDidMount() {
		fetch(this.props.src)
			.then(response => response.json())
			.then(data => {
				console.log(data);
				this.setState({ data })
			});
	}

	render() {
		const _data = this.state.data;
		const children = React.Children.map(this.props.children, child => {
			return React.cloneElement(child, {
				jsonData: _data
			});
		});
		return (
			<div>{ children }</div>
		)
	}
}

// This is how it's used
// SomeCompnent will receive the JSON data
<FetchJsonController src="somefile.json">
  <SomeComponent />
</FetchJsonController>

Example 2: react eznyme fetch api using hooks

//app.js
import React from 'react'
import FetchData from './FetchData'

const fetchUsers = () =>
fetch('https://jsonplaceholder.typicode.com/users').then((res) => res.json())

function App() {
  return (
    <>
      <FetchData fetchUsers={fetchUsers} />
    </>
  )
}

export default App

//fetchdata.js
import React, { useState } from 'react'

function fetchData({ fetchUsers }) {
  const [state, setState] = useState([])

  React.useEffect(() => {
    fetchUsers().then(setState)
  }, [])

  return (
    <>
      {state &&
        state.map((val, id) => (
          <ul key={id}>
            <li>{val.name}</li>
          </ul>
        ))}
    </>
  )
}

export default fetchData

// fetchdata.test.js
import React from 'react'
import { shallow } from 'enzyme'
import FetchData from '../FetchData'

describe('Fetch All Data Hooks', () => {
  let props
  let wrapper
  let useEffect

  const users = [
    { id: 1, name: 'jamal' },
    { id: 2, name: 'karyo' },
    { id: 3, name: 'mirdad' }
  ]

  beforeEach(() => {
    useEffect = jest.spyOn(React, 'useEffect').mockImplementationOnce((f) => f())
    props = { fetchUsers: jest.fn().mockResolvedValue(users) }
    wrapper = shallow(<FetchData {...props} />)
  })

  afterAll(() => {
    jest.clearAllMocks()
  })

  it('result all users', () => {
    expect(useEffect).toHaveBeenCalled()
    expect(props.fetchUsers).toHaveBeenCalled()
    expect(props.fetchUsers).toHaveBeenCalledTimes(1)
    expect(jest.isMockFunction(props.fetchUsers)).toBeTruthy()
  })

  it('find render all users exits count', () => {
    expect(wrapper.find('ul > li')).toHaveLength(3)
    expect(
      wrapper.containsAllMatchingElements([
        <ul>
          <li>jamal</li>
        </ul>,
        <ul>
          <li>karyo</li>
        </ul>,
        <ul>
          <li>mirdad</li>
        </ul>
      ])
    ).toBeTruthy()
  })
})