DEV Community

sandatya widhi
sandatya widhi

Posted on

LATIHAN SOAL

Migrasikan Program React Native Berikut ke Redux

Pada latihan ini, kamu diminta memigrasi dua program (Counter dan ToDoApp) dari penggunaan state lokal (useState) menjadi menggunakan Redux.
Setiap contoh sudah diberikan kode awal sebelum Redux serta langkah migrasinya.


1️⃣ Program Counter (Versi Sebelum Redux)

import React, { useState } from "react";
import { View, Text, Button, StyleSheet } from "react-native";

export default function App() {
  // state lokal untuk counter
  const [value, setValue] = useState(0);

  return (
    <View style={styles.container}>
      <Text style={styles.counterText}>Counter: {value}</Text>

      <View style={styles.row}>
        <Button title="+" onPress={() => setValue((prev) => prev + 1)} />
        <View style={{ width: 12 }} />
        <Button title="-" onPress={() => setValue((prev) => prev - 1)} />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: "center", alignItems: "center" },
  counterText: { fontSize: 40, marginBottom: 20 },
  row: { flexDirection: "row" },
});
Enter fullscreen mode Exit fullscreen mode

Langkah Migrasi ke Redux

  1. Buat file counterReducer.jsx
    Berisi reducer dengan action INCREMENT dan DECREMENT.

  2. Buat store.jsx
    Gunakan combineReducers() dan createStore().

  3. Bungkus root app dengan Provider

   <Provider store={store}>...</Provider>
Enter fullscreen mode Exit fullscreen mode
  1. Hapus useState dari komponen Counter.

  2. Ganti pembacaan value dengan:

   const value = useSelector(state => state.counter.value)
Enter fullscreen mode Exit fullscreen mode
  1. Ganti tombol plus/minus menjadi dispatch:
   dispatch({ type: "INCREMENT" })
   dispatch({ type: "DECREMENT" })
Enter fullscreen mode Exit fullscreen mode
  1. Tes aplikasi. Pastikan counter bekerja sama seperti sebelumnya.


2️⃣ Program ToDoApp (Versi Sebelum Redux)

import React, { useState } from "react";
import { View, TextInput, Button, Text, FlatList, TouchableOpacity, StyleSheet } from "react-native";

export default function TodoScreen() {
  const [text, setText] = useState("");
  const [todos, setTodos] = useState([]);

  const addTodo = () => {
    if (!text.trim()) return;
    const item = { id: Date.now().toString(), text };
    setTodos((prev) => [item, ...prev]);
    setText("");
  };

  const deleteTodo = (id) => {
    setTodos((prev) => prev.filter((t) => t.id !== id));
  };

  return (
    <View style={styles.container}>
      <TextInput placeholder="Tulis todo..." value={text} onChangeText={setText} style={styles.input} />
      <Button title="Tambah" onPress={addTodo} />

      <FlatList
        data={todos}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => (
          <View style={styles.item}>
            <Text style={{ flex: 1 }}>{item.text}</Text>
            <TouchableOpacity onPress={() => deleteTodo(item.id)}>
              <Text style={styles.delete}>Hapus</Text>
            </TouchableOpacity>
          </View>
        )}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { padding: 16, flex: 1 },
  input: { borderWidth: 1, padding: 8, marginBottom: 8 },
  item: { flexDirection: "row", alignItems: "center", paddingVertical: 8 },
  delete: { color: "red", marginLeft: 8 },
});
Enter fullscreen mode Exit fullscreen mode

Langkah Migrasi ToDo ke Redux

  1. Buat todoReducer.jsx Harus menangani:
  • ADD_TODO
  • DELETE_TODO
  1. Buat store.jsx dan bungkus App dengan Provider.

  2. Di TodoScreen:

  • Hapus state:

     const [todos, setTodos] = useState([])
    
  • Ganti dengan:

     const todos = useSelector(state => state.todo.todos)
    
  1. Migrasi fungsi tambah todo:
   dispatch({
     type: "ADD_TODO",
     payload: { id: Date.now(), text }
   })
Enter fullscreen mode Exit fullscreen mode
  1. Migrasi fungsi hapus todo:
   dispatch({
     type: "DELETE_TODO",
     payload: { id }
   })
Enter fullscreen mode Exit fullscreen mode
  1. Tes aplikasi. Pastikan tambah & hapus todo bekerja seperti sebelumnya.

Top comments (0)