What the fetch returns is a list of items. I want to add those into state.
const [state, setState] = useState({
list: {
items: [],
}
});
fetch('http://example.com/list/')
// GET response: [{ name: 'foo' }, { name: 'bar' }, { name: 'baz' }]
.then((resList) => resList.json())
.then((list) => {
list.forEach(({ name }) => {
const itemUrl = `https://example.com/list/${name}`;
fetch(itemUrl)
// GET responses:
// { name: 'foo', desc: '123' }
// { name: 'bar', desc: '456' }
// { name: 'baz', desc: '789' }
.then((itemRes) => itemRes.json())
.then((item) => {
setState((prevState) => ({
...prevState,
list: {
items: [...state.list.items, item]
},
});
})
})
}
})
console.log(state);
// result: [{ name: 'baz', desc: '789' }]
// but wanted: [{ name: 'foo', desc: '123' }, { name: 'bar', desc: '456' }, { name: 'baz', desc: '789' }]
In your case no need to use prevState in setState.
I prepared an example for you. Just be careful at using hooks.
https://codesandbox.io/s/recursing-wood-4npu1?file=/src/App.js:0-567
import React, { useState } from "react"
import "./styles.css"
export default function App() {
const [state, setState] = useState({
list: {
items: [
{ name: "foo", desc: "123" },
{ name: "bar", desc: "456" },
],
},
})
const handleClick = () => {
setState(() => ({
list: {
items: [...state.list.items, { name: "baz", desc: "789" }],
},
}))
}
return (
<div className="App">
<button onClick={handleClick}>Click Me </button>
<hr />
{JSON.stringify(state)}
</div>
)
}
You can't directly access the callback for useState hooks. This is how you can update state after fetching the data:
setState({
...state,
list: {
items:[...state.list.items, item]
},
});
Related
I'm a bit stuck with redux. I want to create reducer that can update state onClick with data that provided in each button.
Here's my TabSlice.ts
interface ITabContext {
tabIndex: number,
posterUrlFetch: string,
tabData: {
fetchUrl: string;
title: string;
}[]
}
const initialState = {
tabIndex: 0,
posterUrlFetch: 'movie/popular',
tabData: [
{ fetchUrl: 'movie/popular', title: 'Trending' },
{ fetchUrl: 'movie/upcoming', title: 'Upcoming' },
{ fetchUrl: 'tv/popular', title: 'TV Series' },
]
}
const tabSlice = createSlice({
name: 'tab',
initialState: initialState as ITabContext,
reducers: {
changeTab(state, action: PayloadAction<ITab>) {
const newItem = action.payload;
return state = {
tabIndex: newItem.tabIndex,
posterUrlFetch: newItem.posterUrlFetch,
tabData: [
{ fetchUrl: newItem.posterUrlFetch, title: newItem.posterUrlFetch },
]
}
}
}
})
Then I dispatch changeTab in my component and create function onClick:
const click = () => dispatch(changeTab({
tabIndex: 1,
posterUrlFetch: 'movie/popular',
tabData: [
{
fetchUrl: 'tv/latest',
title: 'TV Latest'
},
{
fetchUrl: 'movie/popular',
title: 'Popular'
},
{
fetchUrl: 'movie/latest',
title: 'Latest'
},
]
}));
As i click some info updates, but in tabData I have only first object. How to make it to push all data to tabData, not only first one? Thanks!
Remove return state = {} from your reducer function and instead return the object as a whole.
return {
tabIndex: newItem.tabIndex,
posterUrlFetch: newItem.posterUrlFetch,
tabData: newItem.tabData,
};
For the payload's tabData you can pass newItem.tabData
I want to have a drop down in my application which allows the user to add an item to the dropdown. I am using React Sematic UI.
Sematic UI Dropdown ALlowAdditions
I am new to react hooks and I want to know how I can implement the onChange and onAddition function using hooks.
import React, { Component } from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 'English', text: 'English', value: 'English' },
{ key: 'French', text: 'French', value: 'French' },
{ key: 'Spanish', text: 'Spanish', value: 'Spanish' },
{ key: 'German', text: 'German', value: 'German' },
{ key: 'Chinese', text: 'Chinese', value: 'Chinese' },
]
class DropdownExampleAllowAdditions extends Component {
state = { options }
handleAddition = (e, { value }) => {
this.setState((prevState) => ({
options: [{ text: value, value }, ...prevState.options],
}))
}
handleChange = (e, { value }) => this.setState({ currentValue: value })
render() {
const { currentValue } = this.state
return (
<Dropdown
options={this.state.options}
placeholder='Choose Language'
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={this.handleAddition}
onChange={this.handleChange}
/>
)
}
}
export default DropdownExampleAllowAdditions
Any help would be greatly appreciated. Thanks in advance :)
import React, { useState } from "react";
import { Dropdown } from "semantic-ui-react";
const options = [
{ key: "English", text: "English", value: "English" },
{ key: "French", text: "French", value: "French" },
{ key: "Spanish", text: "Spanish", value: "Spanish" },
{ key: "German", text: "German", value: "German" },
{ key: "Chinese", text: "Chinese", value: "Chinese" }
];
const DropDownWithHooks = () => {
const [dropDownOptions, setDropDownOptions] = useState(options);
const [currentValue, setCurrentValue] = useState("");
const handleAddition = (e, { value }) => {
setDropDownOptions((prevOptions) => [
{ text: value, value },
...prevOptions
]);
};
const handleChange = (e, { value }) => setCurrentValue(value);
return (
<Dropdown
options={dropDownOptions}
placeholder="Choose Language"
search
selection
fluid
allowAdditions
value={currentValue}
onAddItem={handleAddition}
onChange={handleChange}
/>
);
};
export default DropDownWithHooks;
Working Sandbox
Assume that this state has initial data like this
const [options, setOptions] = useState({
ProcessType: [
{ value: 1, label: 'Type1' }, { value: 2, label: 'Type2' }
],
ResponsibleUser: [
{ value: 1, label: 'User1' }, { value: 2, label: 'User2' }
]
});
The following function will be called again and again when a post/put called
Help me to complete the commented area as described there.
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
/*
I want here to clear the existing data in options.ProcessType and
map result.data as { value: result.data.id , label: result.data.name },....
and push/concat it into to options.ProcessType but i want to keep the data
inside options.ResponsibleUser unchanged.
result.data is an array of objects like this,
[
{ id: 1 , name: 'Type1', desc : 'desc1', creator: 3, status: 'active' },
{ id: 2 , name: 'Type2', desc : 'desc2', creator: 6, status: 'closed' },
.....
.....
]
*/
})
}
Here is a solution
const fetchProcesses = async () => {
await axios.get(`${process.env.REACT_APP_SERVER_BASE_URL}/processes/`)
.then((result) => {
// solution
setOptions({ResponsibleUser: [...options.ResponsibleUser], ProcessType: result.data.map(row => ({value: row.id, label: row.name}))})
})
}
I'm working on a todo list in my current project.
I can display the todo list but when I click the checkbox to mark a task as complete I get this TypeError:
I've tried to use Google and Stack to find an answer but still can't figure out what it is I'm doing wrong. Why is toggleComplete not a function?
Reducer / todosOne.js
import { createSlice } from '#reduxjs/toolkit'
export const todosOne = createSlice({
name: 'todos',
initialState: [
{ id: 1, text: 'This is a todo item', complete: false },
{ id: 2, text: 'This is a todo item', complete: false },
{ id: 3, text: 'This is a todo item', complete: false },
{ id: 4, text: 'This is a todo item', complete: false },
{ id: 5, text: 'This is a todo item', complete: false },
],
toggleComplete: (store, action) => {
const checkedItem = store.items.find(item => item.id === action.payload)
if (checkedItem) {
checkedItem.complete = !checkedItem.complete
}
}
})
Component / TodoListOne.js
import React from 'react'
import styled from 'styled-components'
import { useSelector, useDispatch } from 'react-redux'
import { todosOne } from '../Reducers/todosOne'
export const TodoListOne = () => {
const dispatch = useDispatch();
const items = useSelector(store => store.todos);
const onChecked = complete => {
dispatch(todosOne.actions.toggleComplete(complete))
}
return (
<>
{items.map(todos => (
<TodoContainer key={todos.id}>
<List>
<label>
<input type="checkbox"
checked={todos.complete}
onChange={() => onChecked(todos.id)}
/>
</label>
</List>
<TodoText>{todos.text}</TodoText>
</TodoContainer>
))}
</>
)
}
It should be
export const todosOne = createSlice({
name: 'todos',
initialState: [
{ id: 1, text: 'This is a todo item', complete: false },
{ id: 2, text: 'This is a todo item', complete: false },
{ id: 3, text: 'This is a todo item', complete: false },
{ id: 4, text: 'This is a todo item', complete: false },
{ id: 5, text: 'This is a todo item', complete: false },
],
// here!
reducers: {
toggleComplete: (store, action) => {
const checkedItem = store.items.find(item => item.id === action.payload)
if (checkedItem) {
checkedItem.complete = !checkedItem.complete
}
}
// here!
}
})
My MobX State tree Model is like this
const ProductItem = types
.model({
name: types.string,
price: types.number
})
.actions(self => ({
changePrice(newPrice) {
self.price = newPrice;
}
}));
const ProductStore = types
.model({
items: types.optional(types.array(ProductItem), [])
})
.actions(self => ({
add(item) {
self.items.push(item);
}
}));
const AppStore = types.model('AppStore', {
productStore: types.maybeNull(ProductStore)
});
AppStore is root store.
I want to create AppStore and initialize below data for ProductStore. I've created below function to initialize and create store :
export const initializeStore = (isServer, snapshot = null) => {
if (isServer) {
AppStore.create({
.....
});
}
return store;
};
I'm not sure how ProductStore should be initialized inside AppStore.create() with this array :
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
any help would be appreciated.
The initial data can be given like this
AppStore.create({
productStore: {
items: [
{
name: 'Product 1',
price: 150
},
{
name: 'Product 2',
price: 170
}
]
}
});
as ProductStore is used under productStore key in your AppStore.