How to make child components use map() from App.js props data? - javascript

My react is 18.2. I want the child component to receive data and use map() from App.js.
I checked the child component received the data, but I don't know why does it can't use map().
It shows this error.
Uncaught TypeError: Cannot read properties of undefined (reading 'map')
So do anyone can fix it? I guess this is render problem, but I don't know how to fix it, thank you.
fetched():
[
{ id:1, date: '2011-01-01T00:00:00.000Z' },
{ id:2, date: '2013-09-03T00:00:00.000Z' },
{ id:3, date: '2012-04-02T00:00:00.000Z' },
{ id:4, date: '2013-12-08T00:00:00.000Z' },
{ id:5, date: '2010-01-23T00:00:00.000Z' },
];
App.js:
import { Child } from './Child';
const Test = () => {
const [toChild, setToChild] = useState()
useEffect(() => {
const data = async () => {
const fetchedData = await fetched();
setToChild(fetchedData)
};
data();
}, []);
const test = () => {
setToChild(fetchedData)
}
}
return(<Child toChild={toChild}>)
Child.js:
const Child = ({ toChild }) => {
const data = toChild;
const getDate = data.map((item) => item.date);

Since the data coming from your fetch is an array of objects, you may want to initialize the state as an empty array useState([]), useEffect will fire once the component has been mounted so at first, toChild will be undefined and that's why you are getting that error.
So basically:
import { useState, useEffect } from 'react'
import { Child } from './Child';
const Test = ()=>{
const [toChild,setToChild] = useState([])
useEffect(() => {
const data = async () => {
const fetchedData = await fetched();
setToChild(fetchedData)
};
data();
}, []);
return <Child toChild={toChild} />

Jsx is already rendered before javascript in react even though you fetch the data from server but html already rendered to the browser.so add any loading component to that. toChild?:<div>loading</div>:<Child toChild={toChild}/>

Related

How to use Hooks inside useEffect?

I wrote a demo here:
import React, { useRef, useEffect, useState } from "react";
import "./style.css";
export default function App() {
// let arrRef = [useRef(), useRef()];
let _data = [
{
title: A,
ref: null
},
{
title: B,
ref: null
}
];
const [data, setData] = useState(null);
useEffect(() => {
getDataFromServer();
}, []);
const getDataFromServer = () => {
//assume we get data from server
let dataFromServer = _data;
dataFromServer.forEach((e, i) => {
e.ref = useRef(null)
});
};
return (
<div>
{
//will trigger some function in child component by ref
data.map((e)=>(<div title={e.title} ref={e.ref}/>))
}
</div>
);
}
I need to preprocess after I got some data from server, to give them a ref property. the error says 'Hooks can only be called inside of the body of a function component' . so I checked the document, it says I can't use hooks inside a handle or useEffect. so is there a way to achieve what I need?
update:
I need to create component base on DB data, so when I create a component I need to give them a ref , I need trigger some function written in child component from their parent component and I use ref to achieve that. that is why I need to pass a ref to child component.

React push Api response in the setState

in my EventForm i have this const, this is a dialog form
this is my EventForm.js
const EventForm = (props) => {
const { setOpenPopup, records, setRecords, setMessage, setOpenSnackbar } = props
const addEvent = () => {
axios.post('https://jsonplaceholder.typicode.com/events', (event)
.then(resp => {
console.log(resp.data)
const newData = [{
title: resp.data.name,
start: resp.data.starts_at,
end: resp.data.ends_at
}]
setRecords([{ ...records, newData}])
//
setOpenPopup(false)
setMessage('New Event added')
setOpenSnackbar(true)
})
.catch([])
}
export default EventForm
EventForm.propTypes = {
setOpenPopup: PropTypes.func,
records: PropTypes.array,
setRecords: PropTypes.func,
setMessage: PropTypes.func,
setOpenSnackbar: PropTypes.func
}
}
in my EventTable.js
const [records, setRecords] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/events')
.then(resp => {
const newData = resp.data.map((item) => ({
title: item.name,
start: item.starts_at,
end: item.ends_at
}))
setRecords(newData)
})
.catch(resp => console.log(resp))
}, [])
fullcalendar...
events={records}
im trying to push the API post response to my setRecords. so when the dialog form close it will not use the GET response. ill just get the new record and render to my view
but im getting an error:
Unhanded Rejection (TypeError): setRecords is not a function
I suspect you are using React Hooks. Make sure that your records state looks like this
const [records, setRecords] = useState([]);
In your axios request, it looks like that you are trying to spread the values of records which is an array to an object. I'd suggest refactoring this to something like this. Instead of trying to spread an array into the object, take the previous state and merge it with the new one.
setRecords(prevRecords => [...prevRecords, ...newData])
Here's an example using React Hooks how the component could look like
import React from "react";
import axios from "axios";
const MyComponent = ({
setOpenPopup,
records,
setRecords,
setMessage,
setOpenSnackbar
}) => {
const addEvent = () => {
axios
.post("https://jsonplaceholder.typicode.com/events", event) // Make sure this is defined somewhere
.then((resp) => {
const { name, starts_at, ends_at } = resp.data;
const newData = [
{
title: name,
start: starts_at,
end: ends_at
}
];
setRecords((prevRecords) => [...prevRecords, ...newData]);
setOpenPopup(false);
setMessage("New Event added");
setOpenSnackbar(true);
})
.catch([]);
};
return (
<div>
<button onClick={addEvent}>Click me </button>
</div>
);
};
export default MyComponent;
If you are not using React Hooks and use Class components, then make sure that you pass setRecords to your component in props. Plus, in your props destructuring, make sure you add this to the props, otherwise, it can lead to unwanted behaviour. Also, move your request function out of the render method and destructure values from the props that you need inside the function. I've also noticed that your axios syntax was incorrect (forgot to close after the event) so I fixed that as well. Here's an example of how you can improve it.
import React from "react";
import axios from "axios";
class MyComponent extends React.Component {
addEvent = () => {
const {
setOpenPopup,
setRecords,
setMessage,
setOpenSnackbar
} = this.props;
axios
.post("https://jsonplaceholder.typicode.com/events", event)
.then((resp) => {
console.log(resp.data);
const newData = [
{
title: resp.data.name,
start: resp.data.starts_at,
end: resp.data.ends_at
}
];
setRecords((prevRecords) => [...prevRecords, ...newData]);
//
setOpenPopup(false);
setMessage("New Event added");
setOpenSnackbar(true);
})
.catch([]);
};
render() {
return (
<div>
<button onClick={() => this.addEvent()}>Click me</button>
</div>
);
}
}
export default MyComponent;

Objects are not valid as a React child (found: object with keys...)

I'm trying to set a state. Here is my code:
import React, { Component, useRef, Fragment, useEffect, useState } from "react";
import axios from "axios";
const Cart = (props) => {
const [useCart, setCart] = useState([]);
useEffect(() => {
(async () => {
const result = await axios
.get('https://example.com/sample')
.then((res) => {
setCart(res.data);
})
.catch((err) => {
console.error(err);
});
})();
}, []);
console.log(useCart);
return (
<div></div>
);
}
export default Cart;
The API returns value like that:
[
{
'id': 5,
'qwe': 'qwe',
'asd': [
{
'aaa': 'aaa',
'bbb': 'bbb'
}
],
'zxc': 'zxc'
},
{
'id': 7,
'qwe': 'qwe',
'asd': [
{
'aaa': 'aaa',
'bbb': 'bbb'
}
],
'zxc': 'zxc'
}
]
I'm not rendering this on component. I'm just trying to console log it. But it give error like that:
Error: Objects are not valid as a React child (found: object with keys {id, qwe, asd, zxc}). If you meant to render a collection of children, use an array instead.
I couldn't understand, where do I do wrong.
Don't know what's going wrong with your code but maybe I can help you debug it. I copied your API's response to a file and simply imported it inside the component to a variable. I then set the state to that variable and everything works fine, all console logs and everything. Check it out here-
https://codesandbox.io/s/angry-ramanujan-3k97v?file=/src/App.js
That tells me the problem could be coming from your useEffect where you are handling your API response.
One change that I made and I think you should do it too when you logout a state variable you should do it inside a lifecycle hook. So you should put your console.log(useCart); inside this
useEffect(()=>{ console.log(useCart); },[useCart])

setup function returns undefined when testing a custom hook usePrevious

I have got code for usePrevious hook from somewhere on internet. The code for usePrevious looks like:
export const usePrevious = (value) => {
const ref = useRef();
useEffect(() => {
ref.current = value;
}, [value]);
return ref.current;
};
Now, I am learing testing react with jest and enzyme. So, I tried to test usePrevious and got some problems. Here is my test case:
import React from 'react';
import { render } from 'enzyme';
import { usePrevious } from './customHooks';
const Component = ({ children, value }) => children(usePrevious(value));
const setup = (value) => {
let returnVal = '';
render(
<Component value={value}>
{
(val) => {
returnVal = val;
return null;
}
}
</Component>,
);
return returnVal;
};
describe('usePrevious', () => {
it('returns something', () => {
const test1 = setup('test');
const test2 = setup(test1);
expect(test2).toBe('test');
});
});
When the test execution completes, I get this error:
Expected: 'test', Received: undefined
Can anyone please let me know why am I getting undefined and is this the correct way to test custom hoooks in react?
After suggestion from comments from #Dmitrii G, I have changed my code to re-render the component (Previously I was re-mounting the component).
Here is the updated code:
import React from 'react';
import PropTypes from 'prop-types';
import { shallow } from 'enzyme';
import { usePrevious } from './customHooks';
const Component = ({ value }) => {
const hookResult = usePrevious(value);
return (
<div>
<span>{hookResult}</span>
<span>{value}</span>
</div>
);
};
Component.propTypes = {
value: PropTypes.string,
};
Component.defaultProps = {
value: '',
};
describe('usePrevious', () => {
it('returns something', () => {
const wrapper = shallow(<Component value="test" />);
console.log('>>>>> first time', wrapper.find('div').childAt(1).text());
expect(wrapper.find('div').childAt(0).text()).toBe('');
// Test second render and effect
wrapper.setProps({ value: 'test2' });
console.log('>>>>> second time', wrapper.find('div').childAt(1).text());
expect(wrapper.find('div').childAt(0).text()).toBe('test');
});
});
But still I am getting the same error
Expected: "test", Received: ""
Tests Passes when settimeout is introduced:
import React from 'react';
import PropTypes from 'prop-types';
import { shallow } from 'enzyme';
import { usePrevious } from './customHooks';
const Component = ({ value }) => {
const hookResult = usePrevious(value);
return <span>{hookResult}</span>;
};
Component.propTypes = {
value: PropTypes.string,
};
Component.defaultProps = {
value: '',
};
describe('usePrevious', () => {
it('returns empty string when component is rendered first time', () => {
const wrapper = shallow(<Component value="test" />);
setTimeout(() => {
expect(wrapper.find('span').text()).toBe('');
}, 0);
});
it('returns previous value when component is re-rendered', () => {
const wrapper = shallow(<Component value="test" />);
wrapper.setProps({ value: 'test2' });
setTimeout(() => {
expect(wrapper.find('span').text()).toBe('test');
}, 0);
});
});
I am not a big fan of using settimeout, so I feel that probably i am doing some mistake. If anyone knows a solution that does not use settimeout, feel free to post here. Thank you.
Enzyme by the hood utilizes React's shallow renderer. And it has issue with running effects. Not sure if it's going to be fixed soon.
Workaround with setTimeout was a surprise to me, did not know it works. Unfortunately, it is not universal approach since you'd need to use that on any change that cases re-render. Really fragile.
As a solution you can use mount() instead.
Also you may mimic shallow rendering with mount() with mocking every nested component:
jest.mock("../MySomeComponent.jsx", () =>
(props) => <span {...props}></span>
);

How to take a jest snapshot after axios fetched data in componentDidMount?

Component to test
class Carousel extends React.Component {
state = {
slides: null
}
componentDidMount = () => {
axios.get("https://s3.amazonaws.com/rainfo/slider/data.json").then(res => {
this.setState({ slides: res.data })
})
}
render() {
if (!slides) {
return null
}
return (
<div className="slick-carousel">
... markup trancated for bravity
</div>
)
}
}
export default Carousel
Test
import React from "react"
import renderer from "react-test-renderer"
import axios from "axios"
import Carousel from "./Carousel"
const slides = [
{
ID: "114",
REFERENCE_DATE: "2018-07-02",
...
},
{
ID: "112",
REFERENCE_DATE: "2018-07-06",
...
},
...
]
jest.mock("axios")
it("", () => {
axios.get.mockImplementationOnce(() => Promise.resolve({ data: slides }))
const tree = renderer.create(<Carousel />).toJSON()
expect(tree).toMatchSnapshot()
})
snapshot only records null, since at the moment of execution I suppose state.slides = null.
Can't put my finger on how to run expectations after axios done fetching the data.
Most of the samples online either use enzyme, or show tests with async functions that return promises. I couldn't find one that would show example only using jest and rendered component.
I tried making test function async, also using done callback, but no luck.
in short:
it("", async () => {
axios.get.mockImplementationOnce(() => Promise.resolve({ data: slides }))
const tree = renderer.create(<Carousel />);
await Promise.resolve();
expect(tree.toJSON()).toMatchSnapshot()
})
should do the job
in details: besides you have mocked call to API data is still coming in async way. So we need toMatchSnapshot call goes to end of microtasks' queue. setTimeout(..., 0) or setImmediate will work too but I've found await Promise.resolve() being better recognizable as "everything below is coming to end of queue"
[UPD] fixed snippet: .toJSON must be after awaiting, object it returns will never be updated
The accepted answer started to fail the next day. After some tweaking, this seems to be working:
import React from "react"
import renderer from "react-test-renderer"
import axios from "axios"
import Carousel from "./Carousel"
jest.mock("axios")
const slides = sampleApiResponse()
const mockedAxiosGet = new Promise(() => ({ data: slides }))
axios.get.mockImplementation(() => mockedAxiosGet)
// eventhough axios.get was mocked, data still comes anychrnonously,
// so during first pass state.slides will remain null
it("returns null initally", () => {
const tree = renderer.create(<Carousel />).toJSON()
expect(tree).toMatchSnapshot()
})
it("uses fetched data to render carousel", () => {
const tree = renderer.create(<Carousel />)
mockedAxiosGet.then(() => {
expect(tree.toJSON()).toMatchSnapshot()
})
})
function sampleApiResponse() {
return [
{
ID: "114",
REFERENCE_DATE: "2018-07-02",
...
},
{
ID: "114",
REFERENCE_DATE: "2018-07-02",
...
},
]
}

Categories