working profile creation and deletion, app loader

This commit is contained in:
erik-sn committed 2020-09-25 19:57:19 -04:00
1 parent a01993e178
commit 5072a31aab
10 files changed
+171 -18

No files matched your search

@@ -10,8 +10,6 @@ function AddTweetStatus() {
const { isSuccessful } = useTweetStatus();
const { t } = useTranslation();
console.log(isSuccessful);
// on the "true" case the tweet was created and the user should
// see their tweet at the top of the list, so there's no need
// to directly prompt them that it was successful.
@@ -5,11 +5,10 @@ import { List } from "../../../ui/components/List";
import { useTweets } from "../hooks/useTweets";
import Tweet from "./Tweet";
const TWEETS_REFRESH_RATE = 5000; // TODO move this to twitter config
const TWEETS_REFRESH_RATE = 50000000; // TODO move this to twitter config
export function TweetList() {
const { tweets } = useTweets();
console.log(tweets);
useEffect(() => {
Nui.send("phone:fetchTweets", {});
@@ -1,12 +1,15 @@
import React, { useState, useCallback } from "react";
import React, { useState, useCallback, useEffect } from "react";
import { blue } from "@material-ui/core/colors";
import { makeStyles, Button } from "@material-ui/core";
import AddCircleIcon from "@material-ui/icons/AddCircle";
import Nui from "../../../os/nui-events/utils/Nui";
import { AppTitle } from "../../../ui/components/AppTitle";
import { AppWrapper } from "../../../ui/components";
import { AppContent } from "../../../ui/components/AppContent";
import { AppLoader } from "../../../ui/components/AppLoader";
import { useApp } from "../../../os/apps/hooks/useApps";
import { useProfile } from "../hooks/useProfile";
import TweetList from "./TweetList";
import AddTweetModal from "./AddTweetModal";
@@ -25,13 +28,33 @@ const useStyles = makeStyles((theme) => ({
},
}));
const MINIMUM_LOAD_TIME = 750;
export const TwitterApp = () => {
const [modalVisible, setModalVisible] = useState(false);
const [minimumLoadPassed, setMimimumLoadPassed] = useState(false);
const classes = useStyles();
const twitter = useApp("TWITTER");
const { profile } = useProfile();
const openModal = useCallback(() => setModalVisible(true), []);
const hideModal = useCallback(() => setModalVisible(false), []);
useEffect(() => {
Nui.send("phone:getOrCreateTwitterProfile", {});
}, []);
useEffect(() => {
const timeout = window.setTimeout(() => {
setMimimumLoadPassed(true);
}, MINIMUM_LOAD_TIME);
return () => window.clearTimeout(timeout);
});
const openModal = () => setModalVisible(true);
const hideModal = () => setModalVisible(false);
// we add a minimum (but short) load time here so that
// there isn't a quick flash of loading and immediately
// another flash to the tweets screen.
const hasLoaded = profile && minimumLoadPassed;
return (
<AppWrapper>
@@ -44,8 +67,14 @@ export const TwitterApp = () => {
<AddCircleIcon color="action" />
</Button>
<AppContent>
<AddTweetModal visible={modalVisible} handleClose={hideModal} />
<TweetList />
{hasLoaded ? (
<>
<AddTweetModal visible={modalVisible} handleClose={hideModal} />
<TweetList />
</>
) : (
<AppLoader />
)}
</AppContent>
</AppWrapper>
);
+4
View File
@@ -1,6 +1,10 @@
import { atom } from "recoil";
export const twitterState = {
profile: atom({
key: "profile",
default: null,
}),
tweets: atom({
key: "tweets",
default: [],
@@ -0,0 +1,7 @@
import { useRecoilValue } from "recoil";
import { twitterState } from "./state";
export const useProfile = () => {
const profile = useRecoilValue(twitterState.profile);
return { profile };
};
@@ -16,18 +16,28 @@ function processTweet(tweet) {
// we store images in the database as a varchar field with
// comma separated links to images, so here we split them
// back into their distinct members
console.log(tweet);
const imageLinks = tweet.images ? tweet.images.split(IMAGE_DELIMITER) : [];
console.log(imageLinks);
const images = imageLinks.map((link) => ({ id: uuidv4(), link }));
return { ...tweet, images };
}
/**
* Service to handle all NUI <> client interactions. We take
* this opportunity to act as a middleware layer between the
* client and the react components. Because I'm terrible with lua
* I have given up on parsing/cleaning database query results there
* there and have moved that logic here instead.
*/
export const useTwitterService = () => {
const setProfile = useSetRecoilState(twitterState.profile);
const setTweets = useSetRecoilState(twitterState.tweets);
const setCreateLoading = useSetRecoilState(twitterState.createTweetLoading);
const setCreateSuccess = useSetRecoilState(twitterState.createTweetSuccess);
const _setProfile = (profile) => {
setProfile(profile[0]); // server returns an array of 1 profile
};
const _setCreateSuccess = (isSuccessful) => {
setCreateSuccess(isSuccessful === 1); // numeric 1 is returned by MySQL on successful query
setCreateLoading(false); // on any result we should set loading to false
@@ -37,9 +47,8 @@ export const useTwitterService = () => {
setTweets(tweets.map(processTweet));
};
useNuiEvent(types.APP_TWITTER, "getOrCreateTwitterProfile", _setProfile);
useNuiEvent(types.APP_TWITTER, "fetchTweets", _setTweets);
useNuiEvent(types.APP_TWITTER, "createTweetLoading", setCreateLoading);
useNuiEvent(types.APP_TWITTER, "createTweetResult", _setCreateSuccess);
return useTweets();
};
+2 -1
View File
@@ -10,14 +10,15 @@ export const useNuiEvent = (app, method, handler, options = {}) => {
}, [handler]);
useEffect(() => {
const eventName = eventNameFactory(app, method);
const eventListener = (event) => {
if (savedHandler.current && savedHandler.current.call) {
const { data } = event;
console.log(eventName, data);
savedHandler.current(data);
}
};
const opts = { capture, passive, once };
const eventName = eventNameFactory(app, method);
window.addEventListener(eventName, eventListener, opts);
return () => window.removeEventListener(eventName, eventListener, opts);
}, [app, method, capture, passive, once]);
+27
View File
@@ -0,0 +1,27 @@
// intended for use on initial application loads
import React from "react";
import { makeStyles, CircularProgress } from "@material-ui/core";
const useStyles = makeStyles((theme) => ({
root: {
height: "400px",
width: "100%",
display: "flex",
flexFlow: "row nowrap",
justifyContent: "center",
alignItems: "center",
},
progress: {
color: "white",
},
}));
export const AppLoader = () => {
const classes = useStyles();
return (
<div className={classes.root}>
<CircularProgress className={classes.progress} size={60} />
</div>
);
};
+7 -1
View File
@@ -9,7 +9,6 @@ end)
local APP_NAME = 'TWITTER'
function sendMessage(method, data)
SendNUIMessage(
{
@@ -40,3 +39,10 @@ RegisterNUICallback('phone:createTweet', function(data)
TriggerEvent('phone:fetchTweets')
end, data)
end)
RegisterNUICallback('phone:getOrCreateTwitterProfile', function()
print('phone:getOrCreateTwitterProfile')
ESX.TriggerServerCallback('phone:getOrCreateTwitterProfile', function(profile)
sendMessage('getOrCreateTwitterProfile', profile)
end)
end)
+75 -2
View File
@@ -1,11 +1,16 @@
ESX = nil
function printO(o)
for key, value in pairs(o) do
print(key, value)
end
end
TriggerEvent('esx:getSharedObject', function(obj)
ESX = obj
end)
ESX.RegisterServerCallback('phone:fetchTweets', function(source, cb)
print('RegisterServerCallback: phone:fetchTweets')
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
@@ -16,7 +21,6 @@ end)
ESX.RegisterServerCallback('phone:createTweet', function(source, cb, data)
print('RegisterServerEvent: phone:createTweet')
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
@@ -31,3 +35,72 @@ ESX.RegisterServerCallback('phone:createTweet', function(source, cb, data)
cb(result)
end)
end)
function getProfile(identifier, cb)
MySQL.Async.fetchAll('SELECT * FROM npwd_twitter_profiles WHERE identifier = @identifier',
{
['identifier'] = identifier,
}, function(result)
cb(result)
end)
end
function getProfileName(identifier, cb)
local defaultProfileName = '' -- handle any edge cases where the user does not exist or their name isn't populated
MySQL.Async.fetchAll('SELECT first_name, last_name FROM users WHERE identifier = @identifier LIMIT 1', {['identifier'] = identifier }, function(users)
-- no user found with this identifier
if next(users) == nil then
cb(defaultProfileName)
return
end
local first_name = users[1].first_name
local last_name = users[1].last_name
if (first_name == "" and last_name == "") then
cb(defaultProfileName)
else
local profileName = first_name .. '_' .. last_name
cb(profileName)
end
end)
end
function createDefaultProfile(identifier, cb)
getProfileName(identifier, function(profileName)
MySQL.Async.execute('INSERT INTO npwd_twitter_profiles (`identifier`, `profile_name`) VALUES (@identifier, @profile_name)',
{
['identifier'] = identifier,
['profile_name'] = profileName,
}, function(result)
if result == 1 then -- if we created the profile then return it
getProfile(identifier, cb)
else -- otherwise just give back the failed result
cb(result)
end
end)
end)
end
-- Retrieve a twitter profile by identifier. If it does not exist then
-- create and return it
function getOrCreateProfile(identifier, cb)
getProfile(identifier, function(retrieveResult)
if next(retrieveResult) == nil then -- profile does not exist, attempt to create it
createDefaultProfile(identifier, function(createResult)
cb(createResult)
end)
else -- profile does exist
cb(retrieveResult)
end
end)
end
ESX.RegisterServerCallback('phone:getOrCreateTwitterProfile', function(source, cb)
local _source = source
local xPlayer = ESX.GetPlayerFromId(_source)
local _identifier = xPlayer.getIdentifier()
getOrCreateProfile(_identifier, function(result)
cb(result)
end)
end)