'How to run the data service from inside the ComponentDidMount again in React
I have a two Api's which gets some source and another to add sources. While displaying the source(images ..) on the screen, in the mean time I am adding some new sources. Since componentDidMount runs only at the start, I can not force componentDidMount to run again whenever a new source added
Here the part of the code:
App.tsx:
export class App extends React.Component<MyProps, MyState> {
constructor(props: any) {
super(props)
this.state = {
sources: [],
currentImage: -1,
}
}
async getSources() {
let allData = await axios.get('/playlist')
return allData.data.data // getting allData from the Api
}
async componentDidMount() {
const sources = await this.getSources()
this.setState(
{
sources: sources,
currentImage: 0,
}
)
}
render() {
<div>
<Playlist onChange={() => this.getSources()} />
.
.
.
</div>
}
}
Playlist.tsx
export function Playlist(props: {onChange: () => void}) {
const {register, handleSubmit} = useForm()
const [data, setData] = useState('')
const onSubmit = async (data: any) => {
console.log('data', await props.onChange())
const url = '/add'
try {
await axios.post(url, data)
await props.onChange(). // trying to call the function after adding new source
} catch (error) {
console.log('Error')
}
}
return (
<form onSubmit={handleSubmit(onSubmit)}>
...
</form>
)
}
As seen in the code, I try to call the function inside the componentDidMount again(after new source is added) to update sources but seems it doesn't work.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
