Reputation: 67
I am trying to update an array of movies when somebody click on "Load films" after he has entered a movie title, but using useState and doing setFilms(films => [...films, data.results]);
(updating the array and adding new movies to the existing empty one) do not work. What should I do? Here is my code:
function HomeScreen({ navigation }) {
const [films, setFilms] = useState([]);
let searchedText = "";
let page = 0;
let totalPages = 0;
const searchInputChanged = text => {
searchedText = text
}
const loadFilms = () => {
if(searchedText.length > 0)
{
getFilmsFromApiWithSearchedText(searchedText, page+1).then(data => {
page = data.page
totalPages = data.total_pages
setFilms(films => [...films, data.results]);
console.log(films)
})
}
}
return (
<View>
<Text>Home</Text>
<TextInput placeholder='Film title' onChangeText={(text) => searchInputChanged(text)} />
<Button title="Load films" onPress={() => loadFilms()} />
</View>
);
}
Upvotes: 1
Views: 916
Reputation: 3820
Did you try this?
setFilms(films => [...films,...data.results]);
Stackblitz: https://stackblitz.com/edit/react-hooks-use-state-4t5sni
When you do [...films,data.results] it will in turn insert results array not the values of results.
Run the following snippet to see
let arr=[1,2,3];
let arr2=[4,5,6];
console.log([...arr,arr2]);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 1
Reputation: 10658
Simple do this:
setFilms([...films, ...data.results])
The useState
hook works a little differently to this.setState
. It's much simpler. No need for a callback based off prevState
anymore.
Upvotes: 1