François
François

Reputation: 67

Edit an array with useState React Native

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

Answers (2)

M A Salman
M A Salman

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

Barry Michael Doyle
Barry Michael Doyle

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

Related Questions