Avi
Avi

Reputation: 23

How to make button add next FlatList item from Redux object

So I have an API that is currently set under the tasks state in my reducer. However, I want to know how to move to the next index within the reducer when I click the button. Currently, if I click the button it constantly adds the current array index name but not the next one since I set the index. Hopefully my code will clarify. This is my Redux App code:

import * as React from 'react';
import {useState, useEffect} from 'react';
import { Text, View, StyleSheet, FlatList, ScrollView, Image, Button } from 'react- 
native';
import Constants from 'expo-constants';
import { Add_Item} from '../redux/actions/index';
import { connect } from 'react-redux';

const mapStateToProps = (state) => {
  return { tasks: state.reducer.tasks };
};
const mapDispatchToProps = {Add_Item};



const url = "https://api.punkapi.com/v2/beers";
export function App ({tasks,Add_Item}){
  const [data, setData] = useState([]);
  React.useEffect (() =>{
    fetch(URL)
    .then (x => x.json())
    .then(json => setData(json))
  })
  return (
    <ScrollView>
      <Button title="Add Text to List" onPress={() => Add_Item(data)} color="blue"/>
      <FlatList data={tasks} renderItem={({ item }) => (
            <View>
              <Text>Name: {item.title[0].name} </Text>
            </View>
          )}
        />
    </ScrollView>
   );
}

export default connect(mapStateToProps, mapDispatchToProps)(App);

This is my action code:

import {ADD_ITEM} from "../actionType/index";

export function Add_Item(task_title){
  return {
    type:ADD_ITEM,
    payload:{
      title:task_title,
    }
  }
}

This is my reducer code:

import { ADD_ITEM } from '../actionType/index';

var initialState = {
tasks: [],
count: 0,
};
export default function (state = initialState, action) {
  if (action.type == ADD_ITEM) {
    return {...state, 
    tasks: [...state.tasks,{title:action.payload.title}]}
  }
  return state;
}

Attached is an image of my results so far. enter image description here

Also how would I add a remove button to remove the last item from the flatlist?

Upvotes: 1

Views: 43

Answers (1)

Drew Reese
Drew Reese

Reputation: 203457

If you are just wanting to one-by-one add the beer names from data to the tasks array then I'd suggest using the tasks array's length as the index into the fetched beer data array for the "beer" you want to create/add a task for. When tasks is empty the length is 0, so data[0] will be selected. When tasks has 5 elements, the length is 5, so data[5] (the sixth element) will be selected.

Example:

import React from "react";
import { connect } from "react-redux";
import {
  Text,
  View,
  StyleSheet,
  FlatList,
  ScrollView,
  Image,
  Button
} from "react-native";
import { actions } from "./tasks.slice";
import "./styles.css";

const url = "https://api.punkapi.com/v2/beers";

function App({ addItem, tasks }) {
  const [data, setData] = React.useState([]);

  React.useEffect(() => {
    fetch(url)
      .then((x) => x.json())
      .then((json) => setData(json));
  }, []);

  return (
    <div className="App">
      <ScrollView>
        <Button
          title="Add Text to List"
          onPress={() => addItem(data[tasks.length])}
          color="blue"
        />
        <FlatList
          data={tasks}
          renderItem={({ item }) => (
            <View>
              <Text>Name: {item.title.name}</Text>
            </View>
          )}
        />
      </ScrollView>
    </div>
  );
}

const mapStateToProps = (state) => ({
  tasks: state.tasks.tasks
});

const mapDispatchToProps = {
  addItem: actions.addItem
};

export default connect(mapStateToProps, mapDispatchToProps)(App);

The tasks reducer should be updated to save the entire payload instead of an undefined title property that doesn't exist on the data[] element objects.

export default function (state = initialState, action) {
  if (action.type === ADD_ITEM && action.payload) {
    return {
      ...state, 
      tasks: [...state.tasks, { title: action.payload }]
    };
  }
  return state;
}

Edit how-to-make-button-add-next-flatlist-item-from-redux-object

enter image description here

Upvotes: 0

Related Questions