From 7377c316db072287798cd7c3374bec47eff7e9f7 Mon Sep 17 00:00:00 2001 From: James Ketrenos Date: Mon, 16 Aug 2021 18:44:00 -0700 Subject: [PATCH] Use useReducer to forceUpdate the view when Whiskies deep object changes Signed-off-by: James Ketrenos --- whisky-business/App.tsx | 72 +++++++++++++++++++++++++++-------------- 1 file changed, 48 insertions(+), 24 deletions(-) diff --git a/whisky-business/App.tsx b/whisky-business/App.tsx index 6b5e777..c354e68 100644 --- a/whisky-business/App.tsx +++ b/whisky-business/App.tsx @@ -1,5 +1,5 @@ import { StatusBar } from 'expo-status-bar'; -import React, { useState } from 'react'; +import React, { useState, useReducer } from 'react'; import { StyleSheet, Text, TextInput, TouchableOpacity, View } from 'react-native'; import { request, GraphQLClient, gql } from 'graphql-request'; import moment from 'moment'; @@ -89,9 +89,55 @@ export default function App() { [search, setSearch] = useState(""), [lastSearch, setLastSearch] = useState(""), [activeWhisky, setActiveWhisky] = useState(""); + + const [, forceUpdate] = useReducer(x => x + 1, 0); + + const updateWhisky = (code : string) => { + const query = gql` { + Whisky(code: "${code}") { + inventories { + location { + code + address + city + phone + longitude + latitude + } + quantity + updated + } + code + size + description + updated + quantity + } + }`; + + client.request(query) + .then(data => { + for (let i = 0; i < whiskies.length; i++) { + if (whiskies[i].code == data.Whisky.code) { + whiskies[i] = data.Whisky; + break; + } + } + setWhiskies(whiskies); + forceUpdate(); + }) + .catch (error => { + console.error(error); + }); + }; const onPress = (code : string) => { - setActiveWhisky(code == activeWhisky ? "" : code); + if (code == activeWhisky) { + setActiveWhisky(""); + } else { + setActiveWhisky(code); + updateWhisky(code); + } }; const items = whiskies ? whiskies @@ -109,28 +155,6 @@ export default function App() { ); }) : []; - const query = gql` { - Whiskies { - code - description - price - size - lastSeen - inventories { - location { - code - address - city - phone - longitude - latitude - } - quantity - updated - } - } - }`; - const submitSearch = () => { if (search.trim() == "") { setWhiskies([]);