react-redux#useStore JavaScript Examples

The following examples show how to use react-redux#useStore. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TracksEnrollStages.js    From codeclannigeria-frontend with MIT License 6 votes vote down vote up
function TracksEnrollStages({ id }) {
  const [trackData, settrackData] = useState(null);
  const [stageData, setStageData] = useState(null);
  const store = useStore().getState().tracks;
  const getTrackStages = useCallback(
    async id => {
      try {
        let res = await codeClanApi.get(`tracks/${id}/stages`);
        setStageData(res.data);
        let resData = store.data.items.filter(data => data.id === id);
        settrackData(resData[0]);
      } catch (e) {
        // console.log(e);
      }
    },
    [store.data.items]
  );
  useEffect(() => {
    getTrackStages(id);
  }, [getTrackStages, id]);

  return (
    <div className="tracks-stages-card">
      {trackData ? (
        <TracksStagesCard trackData={trackData} stageData={stageData} />
      ) : (
        <CustomLoader />
      )}
    </div>
  );
}
Example #2
Source File: MentorDashboardHOC.js    From codeclannigeria-frontend with MIT License 5 votes vote down vote up
function MentorDashboardLayout(Component) {
  return function DashboardPage(props) {
    const [showSidebar, setshowSidebar] = useState(false);
    const [userLoading, setUserLoading] = useState(false);

    const toggleSidebar = () => {
      setshowSidebar(!showSidebar);
    };
    const store = useStore();
    const userState = store.getState().user.data;
    const dispatch = useDispatch();
    const APIerror = useSelector(state => state.API.error);

    useEffect(() => {
      if (APIerror) {
        message.error(APIerror);
      }
    }, [APIerror]);

    useEffect(() => {
      if (!userState) {
        setUserLoading(true);
        dispatch(getUserProfileApi());
      }
      setUserLoading(false);
    }, [userState, dispatch, userLoading]);
    const { url } = props.match;

    return (
      <div>
        <MentorDashboardStyled>
          <MentorDashboardSidebar path={url} showSidebar={showSidebar} />
          <DashboardHeader
            toggleSidebar={toggleSidebar}
            showSidebar={showSidebar}
          />
          <div className="dashboard-wrap row">
            <div className="dashboard-content col-md-10 container ">
              <Component {...props} />
            </div>
          </div>
        </MentorDashboardStyled>
      </div>
    );
  };
}
Example #3
Source File: NameWithInjector.js    From module-federation-examples with MIT License 5 votes vote down vote up
NameWithInjector = () => {
  const store = useStore();

  React.useEffect(() => store.injectReducer("name", nameReducer), []);

  return <NameInput />;
}
Example #4
Source File: DeviceDetail.js    From edge-frontend with Apache License 2.0 4 votes vote down vote up
GeneralInformationTab = () => {
  const writePermissions = useSelector(
    ({ permissionsReducer }) => permissionsReducer?.writePermissions
  );

  const { greenbootStatus, rhcHealth } = useSelector(
    ({ systemProfileStore }) => ({
      greenbootStatus: systemProfileStore?.systemProfile?.greenboot_status,
      rhcHealth: null,
    })
  );

  return (
    <Suspense fallback="">
      <GeneralInformation
        store={useStore()}
        writePermissions={writePermissions}
        SystemCardWrapper={(props) => (
          <Suspense fallback="">
            <SystemCard
              {...props}
              hasCPUs={false}
              hasSockets={false}
              hasCores={false}
              hasCPUFlags={false}
              hasRAM={false}
              hasSAP={false}
              extra={[
                {
                  title: (
                    <TitleWithPopover
                      title="GreenBoot Status"
                      content="This is a description about greenboot status"
                    />
                  ),
                  value: <GreenbootStatus status={greenbootStatus} />,
                },
              ]}
            />
          </Suspense>
        )}
        OperatingSystemCardWrapper={(props) => (
          <Suspense fallback="">
            {' '}
            <InfrastructureCard {...props} />
          </Suspense>
        )}
        BiosCardWrapper={(props) => (
          <Suspense fallback="">
            {' '}
            <ImageInformationCard {...props} />
          </Suspense>
        )}
        InfrastructureCardWrapper={(props) => (
          <Suspense fallback="">
            <BiosCard {...props} />
          </Suspense>
        )}
        ConfigurationCardWrapper={(props) => (
          <Suspense fallback="">
            <OperatingSystemCard {...props} hasKernelModules={true} />
          </Suspense>
        )}
        CollectionCardWrapper={(props) => (
          <Suspense fallback="">
            <CollectionCard
              {...props}
              extra={[
                {
                  title: 'RHC Health (broker functioning)',
                  value: statusHelper[rhcHealth?.toUpperCase()] || (
                    <Tooltip content="Unknown service status">
                      <OutlinedQuestionCircleIcon className="ins-c-inventory__detail--unknown" />
                    </Tooltip>
                  ),
                },
              ]}
            />
          </Suspense>
        )}
      />
    </Suspense>
  );
}
Example #5
Source File: table.js    From actual with MIT License 4 votes vote down vote up
export function useTableNavigator(data, fields, opts = {}) {
  let getFields = typeof fields !== 'function' ? () => fields : fields;
  let { initialEditingId, initialFocusedField, moveKeys } = opts;
  let [editingId, setEditingId] = useState(initialEditingId || null);
  let [focusedField, setFocusedField] = useState(initialFocusedField || null);
  let containerRef = useRef();

  // See `onBlur` for why we need this
  let store = useStore();
  let modalStackLength = useRef(0);

  // onEdit is passed to children, so make sure it maintains identity
  let onEdit = useCallback((id, field) => {
    setEditingId(id);
    setFocusedField(id ? field : null);
  }, []);

  useEffect(() => {
    modalStackLength.current = store.getState().modals.modalStack.length;
  }, []);

  function flashInput() {
    // Force the container to be focused which suppresses the "space
    // pages down" behavior. If we don't do this and the user presses
    // up + space down quickly while nothing is focused, it would page
    // down.
    containerRef.current.focus();

    // Not ideal, but works for now. Let the UI show the input
    // go away, and then bring it back on the same row/field
    onEdit(null);

    setTimeout(() => {
      onEdit(editingId, focusedField);
    }, 100);
  }

  function onFocusPrevious() {
    let idx = data.findIndex(item => item.id === editingId);
    if (idx > 0) {
      let item = data[idx - 1];
      let fields = getFields(item);
      onEdit(item.id, fields[fields.length - 1]);
    } else {
      flashInput();
    }
  }

  function onFocusNext() {
    let idx = data.findIndex(item => item.id === editingId);
    if (idx < data.length - 1) {
      let item = data[idx + 1];
      let fields = getFields(item);
      onEdit(item.id, fields[0]);
    } else {
      flashInput();
    }
  }

  function moveHorizontally(dir) {
    if (editingId) {
      let fields = getFields(data.find(item => item.id === editingId));
      let idx = fields.indexOf(focusedField) + dir;

      if (idx < 0) {
        onFocusPrevious();
      } else if (idx >= fields.length) {
        onFocusNext();
      } else {
        setFocusedField(fields[idx]);
      }
    }
  }

  function moveVertically(dir) {
    if (editingId) {
      let idx = data.findIndex(item => item.id === editingId);
      let nextIdx = idx;

      while (true) {
        nextIdx = nextIdx + dir;
        if (nextIdx >= 0 && nextIdx < data.length) {
          const next = data[nextIdx];
          if (getFields(next).includes(focusedField)) {
            onEdit(next.id, focusedField);
            break;
          }
        } else {
          flashInput();
          break;
        }
      }
    }
  }

  function onMove(dir) {
    switch (dir) {
      case 'left':
        moveHorizontally(-1);
        break;
      case 'right':
        moveHorizontally(1);
        break;
      case 'up':
        moveVertically(-1);
        break;
      case 'down':
        moveVertically(1);
        break;
      default:
        throw new Error('Unknown direction: ' + dir);
    }
  }

  function getNavigatorProps(userProps) {
    return {
      ...userProps,

      innerRef: containerRef,

      onKeyDown: e => {
        userProps && userProps.onKeyDown && userProps.onKeyDown(e);
        if (e.isPropagationStopped()) {
          return;
        }

        let fieldKeys =
          moveKeys && moveKeys[focusedField] && moveKeys[focusedField];

        if (fieldKeys && fieldKeys[e.keyCode]) {
          e.preventDefault();
          e.stopPropagation();

          onMove(fieldKeys[e.keyCode]);
        } else {
          switch (e.keyCode) {
            case keys.UP:
            case keys.K:
              if (e.target.tagName !== 'INPUT') {
                onMove('up');
              }
              break;

            case keys.DOWN:
            case keys.J:
              if (e.target.tagName !== 'INPUT') {
                onMove('down');
              }
              break;

            case keys.ENTER:
            case keys.TAB:
              e.preventDefault();
              e.stopPropagation();

              onMove(
                e.keyCode === keys.ENTER
                  ? e.shiftKey
                    ? 'up'
                    : 'down'
                  : e.shiftKey
                    ? 'left'
                    : 'right'
              );
              break;
            default:
          }
        }
      },

      onBlur: e => {
        // We want to hide the editing field if the user clicked away
        // from the table. We use `relatedTarget` to figure out where
        // the focus is going, and if it's nothing (the user clicked
        // somewhere that doesn't have an editable field) or if it's
        // anything outside of the table, clear editing.
        //
        // Also important: only do this if the app is focused. The
        // blur event is fired when the app loses focus and we don't
        // want to hide the input.

        // The last tricky edge case: we don't want to blur if a new
        // modal just opened. This way the field still shows an
        // input, and it will be refocused when the modal closes.
        let prevNumModals = modalStackLength.current;
        let numModals = store.getState().modals.modalStack.length;

        if (
          document.hasFocus() &&
          (e.relatedTarget == null ||
            !containerRef.current.contains(e.relatedTarget)) &&
          prevNumModals === numModals
        ) {
          onEdit(null);
        }
      }
    };
  }

  return { onEdit, editingId, focusedField, getNavigatorProps };
}
Example #6
Source File: DashboardLayout.js    From codeclannigeria-frontend with MIT License 4 votes vote down vote up
DashboardLayout = Component => {
  return function DashboardPage(props) {
    const [showSidebar, setshowSidebar] = useState(false);
    const [userLoading, setUserLoading] = useState(false);
    const toggleSidebar = () => {
      setshowSidebar(!showSidebar);
    };
    const tabs = [
      // {
      //   id: 1,
      //   icon: <i class="fas fa-home fa-2x"></i>,
      //   link: '/dashboard',
      //   name: '',
      // },
      {
        id: 1,
        icon: <i class="fas fa-user-friends"></i>,
        link: '/dashboard/mentee/mentor',
        name: 'Mentor',
      },
      {
        id: 2,
        icon: <i class="fas fa-code"></i>,
        link: '/dashboard/track',
        name: 'Tracks',
      },
      {
        id: 3,
        icon: <i class="fas fa-tasks"></i>,
        link: '/dashboard/pending-task',
        name: 'Tasks',
      },
      {
        id: 4,
        icon: <i class="fas fa-user-ninja"></i>,
        link: '/dashboard/mentee/profile',
        name: 'Profile',
      },

      {
        id: 5,
        icon: <i class="fas fa-sliders-h"></i>,
        link: '#',
        name: 'Settings',
      },
    ];
    const { url } = props.match;

    const store = useStore();
    const userState = store.getState().user.data;
    const dispatch = useDispatch();
    const APIerror = useSelector(state => state.API.error);

    useEffect(() => {
      if (!userState) {
        setUserLoading(true);
        dispatch(getUserProfileApi());
        dispatch(getUserMentorProfileApi());
      }
      setUserLoading(false);
    }, [userState, dispatch, userLoading]);

    useEffect(() => {
      if (APIerror) {
        message.error(APIerror);
      }
    }, [APIerror]);
    return (
      <MentorDashboardStyled>
        <DashboardSidebar tabs={tabs} path={url} showSidebar={showSidebar} />

        {!userLoading ? (
          <React.Fragment>
            <DashboardHeader
              toggleSidebar={toggleSidebar}
              showSidebar={showSidebar}
            />
            <div className="dashboard-wrap row">
              <div className="dashboard-content col-md-9 container">
                <Component {...props} />
              </div>
            </div>
          </React.Fragment>
        ) : (
          <CustomLoader />
        )}
      </MentorDashboardStyled>
    );
  };
}
Example #7
Source File: index.js    From designcode-app with MIT License 4 votes vote down vote up
export default function Notifications() {
  const [translateY, setTranslateY] = useState(new Animated.Value(30));
  const [opacity, setOpacity] = useState(new Animated.Value(0));
  const [top, setTop] = useState(new Animated.Value(3000));

  const store = useStore();

  useEffect(() => {
    if (store.getState().app.action == "openNotif") {
      Animated.parallel([
        Animated.spring(translateY, {
          toValue: 0,
          useNativeDriver: false,
        }),
        Animated.timing(opacity, {
          toValue: 1,
          duration: 500,
          useNativeDriver: false,
        }),
        Animated.timing(top, {
          toValue: 0,
          duration: 0,
          useNativeDriver: false,
        }),
      ]).start();
    }

    if (store.getState().app.action == "closeNotif") {
      Animated.parallel([
        Animated.spring(translateY, {
          toValue: 30,
          useNativeDriver: false,
        }),
        Animated.timing(opacity, {
          toValue: 0,
          duration: 500,
          useNativeDriver: false,
        }),
        Animated.timing(top, {
          toValue: 3000,
          duration: 0,
          useNativeDriver: false,
        }),
      ]).start();
    }
  }, [store.getState().app.action]);

  function closeNotif() {
    store.dispatch({ type: "CLOSE_NOTIF" });
  }

  return (
    <AnimatedContainer style={{ top: top }}>
      <TouchableOpacity
        onPress={closeNotif}
        style={{
          position: "absolute",
          top: 40,
          left: "50%",
          marginLeft: -22,
          zIndex: 100,
        }}
      >
        <CloseButton style={{ elevation: 20 }}>
          <Ionicons name="ios-close" size={44} color="#546bfb" />
        </CloseButton>
      </TouchableOpacity>
      <SafeAreaView>
        <ScrollView style={{ padding: 20 }}>
          <Wrapper>
            <Subtitle>New</Subtitle>
            {items.map((item, index) => (
              <AnimatedItem
                key={index}
                style={{
                  opacity: opacity,
                  transform: [{ translateY: translateY }],
                }}
              >
                <Header>
                  <Logo source={{ uri: item.logo }} resizeMode="contain" />
                  <Title>{item.title}</Title>
                  <DateContainer>
                    <Date>{item.date}</Date>
                  </DateContainer>
                </Header>
                <Text>{item.text}</Text>
              </AnimatedItem>
            ))}
          </Wrapper>
        </ScrollView>
      </SafeAreaView>
    </AnimatedContainer>
  );
}
Example #8
Source File: CheckoutForm.jsx    From real-estate-site with MIT License 4 votes vote down vote up
export default function CheckoutForm(props) {
  const { userReducer } = useStore().getState();
  const stripe = useStripe();
  const elements = useElements();
  const dispatch = useDispatch();

  const handleSubmit = async event => {
    event.preventDefault();

    if (!stripe || !elements || !state.foundUserId) {
      return;
    }

    const result = await stripe.confirmCardPayment(state.userId, {
      payment_method: {
        card: elements.getElement(CardElement),
        billing_details: {
          name: userReducer.user.email
        }
      }
    });

    if (result.error) {
      // Show error to your customer (e.g., insufficient funds)
      console.log(result.error.message);
    } else {
      // The payment has been processed!
      if (result.paymentIntent.status === "succeeded") {
        const { jwt } = userReducer;
        axios.defaults.headers.common["Authorization"] = `Bearer ${jwt}`;

        axios
          .post(`${baseUrl}/user/addcredits`, { ...result })
          .then(res => {
            dispatch(creditAddSuccess(res.data));
            state.requested = false;
            state.foundUserId = false;
          })
          .catch(console.error);
      }
    }
  };

  useEffect(() => {
    if (userReducer) {
      if (!state.amountInCents) {
        state.amountInCents = +props.amountInCents;
      } else if (!state.requested) {
        state.requested = true;
        const { jwt } = userReducer;
        axios.defaults.headers.common["Authorization"] = `Bearer ${jwt}`;

        axios
          .get(`${baseUrl}/payment/${state.amountInCents}`)
          .then(res => {
            // console.log(res.data);
            state.userId = res.data.client_secret;
            state.foundUserId = true;
          })
          .catch(console.error);
      }
    }
  });

  return (
    <Fragment>
      <div className="alert alert-info mt-3" role="alert">
        You are going to top up your account for {state.amountInCents / 100}{" "}
        EUR. It is {state.amountInCents / 100} new advertisements. 1
        advertisement price is 1 EUR.
      </div>

      <div className="row">
        {userReducer ? (
          <form onSubmit={handleSubmit} className="col-12">
            <CardSection />
            <br />
            <button disabled={!stripe} className="btn btn-success">
              Confirm order
            </button>
          </form>
        ) : (
          <div class="alert alert-warning mt-3" role="alert">
            Sorry to TopUp your account, you should login first
          </div>
        )}
      </div>
    </Fragment>
  );
}
Example #9
Source File: index.jsx    From Pandaudio with MIT License 4 votes vote down vote up
RoomPage = props => {
  const {
    location: {
      state: { isHost, roomInfo },
    },
  } = props;

  const classes = useStyles();
  const [open, setOpen] = useState(false);
  const [songQueueReady, setSongQueueReady] = useState(false);
  const [initialPlay, setInitialPlay] = useState(false);
  const dispatch = useDispatch();
  const store = useStore();
  const playerState = useSelector(state => state.player);
  const songQueueState = useSelector(state => state.songQueue);
  // hard coded pokemon song

  useEffect(() => {
    // setup fetch data method when component loads intially
    setup();

    // join song room when page is loaded is loaded
    socket.emit('join_room', `song${roomInfo.id}`);

    // onload of room post message to websocket asking for the current song URI and time
    if (!isHost) {
      socket.emit('requestPlayInfo', {
        room: `song${roomInfo.id}`,
        targetGuest: socket.id,
      });
    }

    if (isHost) {
      socket.on('requestPlayInfo', data => {
        // emit a special play message back to ONLY that guest requester
        console.log('host receive requests for play Info', data);
        getPlayerInfoAndEmit(window.globalSpotifyPlayer, data);
      });
    }

    // add listeners of websocket to play a song at a certain time
    socket.on('play', data => {
      console.log('Incoming play message: ', data);

      // only play song if the targetGuest is my own socket.id or if its falsy (broadcast to everyone to play)
      if (data.targetGuest === socket.id || !data.targetGuest) {
        playSong(window.globalSpotifyPlayer, data.spotify_uris, data.start_time);
      }
    });

    // add listener of websocket to pause a song
    socket.on('pause', data => {
      console.log('Incoming message: ', data);
      pauseSong(window.globalSpotifyPlayer);
    });
  }, []);

  const setup = () => {
    // async call to get all songs and dispatch to songQueue store

    fetch(`/api/v1/rooms/${roomInfo.id}/songs`, {
      method: 'GET',
      headers: {
        'Content-Type': 'appplication/json',
      },
    })
      .then(response => response.json())
      .then(data => {
        console.log('grabbed all the songs from db', data);
        dispatch({ type: SONG_QUEUE_UPDATE, payload: data });
        setSongQueueReady(true);
      });
  };

  const getPlayerInfoAndEmit = (player, requestData) => {
    const {
      _options: { getOAuthToken },
    } = player;

    getOAuthToken(access_token => {
      fetch(`https://api.spotify.com/v1/me/player`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          Authorization: `Bearer ${access_token}`,
        },
      })
        .then(response => response.json())
        .then(playerInfo => {
          const {
            item: { uri },
            progress_ms,
          } = playerInfo;

          const trackWindow = store.getState().player.data.track_window;
          const currentTrack = trackWindow.current_track;
          const nextTracks = trackWindow.next_tracks;
          const tracks = [currentTrack, ...nextTracks];

          socket.emit('play', {
            room: `song${roomInfo.id}`,
            spotify_uris: tracks.map(track => track.uri),
            start_time: progress_ms,
            targetGuest: requestData.targetGuest,
          });
        });
    });
  };

  // helper to play a song
  const playSong = (player, spotify_uris, start_time) => {
    // function to play song from spotify API
    const play = ({
      spotify_uris,
      playerInstance: {
        _options: { getOAuthToken, id },
      },
      start_time = 0,
    }) => {
      getOAuthToken(access_token => {
        console.log('we are in the get oauth', access_token, id);
        console.log('this is the spotify uri', spotify_uris);
        fetch(`https://api.spotify.com/v1/me/player/play?device_id=${id}`, {
          method: 'PUT',
          body: JSON.stringify({ uris: spotify_uris, position_ms: start_time }),
          headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${access_token}`,
          },
        });
      });
    };

    console.log('before we call play', player);

    play({
      playerInstance: player,
      spotify_uris,
      start_time,
    });
  };

  const pauseSong = player => {
    player.pause().then(() => {
      console.log('Paused!');
    });
  };

  const handlePlay = e => {
    let uris;

    if (!initialPlay) {
      uris = songQueueState.data.map(song => song.uri);
      setInitialPlay(true);
    } else {
      const trackWindow = store.getState().player.data.track_window;
      const currentTrack = trackWindow.current_track;
      const nextTracks = trackWindow.next_tracks;
      const tracks = [currentTrack, ...nextTracks];

      uris = tracks.map(track => track.uri);
    }

    socket.emit('play', {
      room: `song${roomInfo.id}`,
      spotify_uris: uris,
      start_time: playerState.data.position || 0,
    });
  };

  const handlePause = e => {
    socket.emit('pause', {
      room: `song${roomInfo.id}`,
    });
  };

  const toggleOpen = e => {
    e.preventDefault();
    setOpen(!open);
  };

  const { location } = props;
  const { track_window } = playerState.data;

  let songName, artists, albumName, albumArt, isPaused;

  if (track_window) {
    songName = track_window.current_track.name;
    artists = track_window.current_track.artists;
    albumName = track_window.current_track.album.name;
    albumArt = track_window.current_track.album.images[0].url;
    isPaused = playerState.data.paused;
  }

  return (
    <div className="room-page">
      <div className="room-content">
        {location.state.isHost ? (
          <div className="addsong-container">
            <button className="btn-addsong" type="submit" onClick={toggleOpen}>
              Add Song
            </button>
            <HostDisableRoomButton roomId={location.state.roomInfo.id} />
            <Modal open={open} onClose={toggleOpen} className={classes.modal}>
              <div className={classes.paper}>
                <SongSearch roomId={location.state.roomInfo.id} />
              </div>
            </Modal>
          </div>
        ) : null}
        <div className="room-header">
          <h2>{roomInfo.room_name}</h2>
          <p>Back to Lobby</p>
        </div>
        <div className="room-player">
          <div className="player-cover">
            {albumArt && <img src={albumArt} />}
          </div>
          <div className="player-content">
            <div className="player-playing">
              <p>{!track_window ? 'Waiting for tunes' : isPaused ? 'Paused' : 'Now Playing'}</p>
            </div>
            <div className="player-details">
              <h3>{songName || 'Song Name'}</h3>
              <p>{albumName || 'Album Name'}</p>
              <p>0:00 / 2:30</p>
            </div>
            <div className="player-btn">
              {isHost && playerState.ready && songQueueReady ? (
                <PlaybackControls
                  playSong={() => {
                    handlePlay();
                  }}
                  pauseSong={() => {
                    handlePause();
                  }}
                />
              ) : null}
            </div>
          </div>
        </div>
      </div>
      <div className="sidebar">
        <div className="room-queue">
          <h1>Song Queue</h1>
        </div>
        <div className="room-chat">
          <Chat roomId={roomInfo.id} />
        </div>
      </div>
    </div>
  );
}