react eznyme fetch api using hooks

Solutions on MaxInterview for react eznyme fetch api using hooks by the best coders in the world

showing results for - "react eznyme fetch api using hooks"
Mila
12 Jun 2016
1//app.js
2import React from 'react'
3import FetchData from './FetchData'
4
5const fetchUsers = () =>
6fetch('https://jsonplaceholder.typicode.com/users').then((res) => res.json())
7
8function App() {
9  return (
10    <>
11      <FetchData fetchUsers={fetchUsers} />
12    </>
13  )
14}
15
16export default App
17
18//fetchdata.js
19import React, { useState } from 'react'
20
21function fetchData({ fetchUsers }) {
22  const [state, setState] = useState([])
23
24  React.useEffect(() => {
25    fetchUsers().then(setState)
26  }, [])
27
28  return (
29    <>
30      {state &&
31        state.map((val, id) => (
32          <ul key={id}>
33            <li>{val.name}</li>
34          </ul>
35        ))}
36    </>
37  )
38}
39
40export default fetchData
41
42// fetchdata.test.js
43import React from 'react'
44import { shallow } from 'enzyme'
45import FetchData from '../FetchData'
46
47describe('Fetch All Data Hooks', () => {
48  let props
49  let wrapper
50  let useEffect
51
52  const users = [
53    { id: 1, name: 'jamal' },
54    { id: 2, name: 'karyo' },
55    { id: 3, name: 'mirdad' }
56  ]
57
58  beforeEach(() => {
59    useEffect = jest.spyOn(React, 'useEffect').mockImplementationOnce((f) => f())
60    props = { fetchUsers: jest.fn().mockResolvedValue(users) }
61    wrapper = shallow(<FetchData {...props} />)
62  })
63
64  afterAll(() => {
65    jest.clearAllMocks()
66  })
67
68  it('result all users', () => {
69    expect(useEffect).toHaveBeenCalled()
70    expect(props.fetchUsers).toHaveBeenCalled()
71    expect(props.fetchUsers).toHaveBeenCalledTimes(1)
72    expect(jest.isMockFunction(props.fetchUsers)).toBeTruthy()
73  })
74
75  it('find render all users exits count', () => {
76    expect(wrapper.find('ul > li')).toHaveLength(3)
77    expect(
78      wrapper.containsAllMatchingElements([
79        <ul>
80          <li>jamal</li>
81        </ul>,
82        <ul>
83          <li>karyo</li>
84        </ul>,
85        <ul>
86          <li>mirdad</li>
87        </ul>
88      ])
89    ).toBeTruthy()
90  })
91})