The initial value for Redux-thunk input

I have created a simplistic Single Page Application (SPA) using the thunk library. This application utilizes the GitHub API to fetch a list of repositories. Initially, I had implemented an example with a class-based presentational component that included local state. However, in order to provide a simplified example, I refactored the code to utilize functional components and removed the local state mechanism. Instead, I utilized the "ref" attribute to access the input value. The updated code is functioning correctly.

  1. Is there a way to set a default value within the input field so that it automatically populates when the app is launched?
  2. I'm facing some confusion regarding the process of removing combineReducers and utilizing a single reducer. Whenever I attempt to create the store with only one reducer, my application breaks. Can you guide me on this issue?

Please find the code below:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { applyMiddleware, combineReducers, createStore } from "redux";
import { connect, Provider } from "react-redux";
import thunk from "redux-thunk";
import "./index.css";

// actions.js
const addRepos = repos => ({ type: "ADD_REPOS", repos });
const clearRepos = () => ({ type: "CLEAR_REPOS" });
const getRepos = username => async dispatch => {
  try {
    const url = `https://api.github.com/users/${username}/repos`;
    const response = await fetch(url);
    const responseBody = await response.json();
    dispatch(addRepos(responseBody));
  } catch (error) {
    console.log(error);
    dispatch(clearRepos());
  }
};

// reducers.js
const repos = (state = [], action) => {
  switch (action.type) {
    case "ADD_REPOS":
      return action.repos;
    case "CLEAR_REPOS":
      return [];
    default:
      return state;
  }
};

const rootreducer = combineReducers({ repos });

const store = createStore(rootreducer, applyMiddleware(thunk));

// App.js
function App(props) {
  var textInput;
  var setTextInputRef = element => { textInput = element; };
  var submit = () => props.getRepos(textInput.value);
  return (
    <div>
      <h1>Github username: </h1>
      <input type="text" ref={setTextInputRef} />
      <button onClick={submit}>Get All Repos</button>
      <ul>
        {props.repos.map((repo, index) => (<li key={index}><a href={repo.html_url}>{repo.name}</a></li> ))}
      </ul>
    </div>
  );
}

// AppContainer.js
const mapStateToProps = state => ({ repos: state.repos });
const mapDispatchToProps = { getRepos };
const AppContainer = connect(mapStateToProps, mapDispatchToProps)(App);

ReactDOM.render(<Provider store={store}><AppContainer /></Provider>, document.getElementById("root"));

Answer №1

1.) To achieve this purpose, you can utilize the defaultValue feature.

2.) If you decide not to employ combineReducers(), you will need to modify your mapStateToProps().

This is one method to accomplish it:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { applyMiddleware, combineReducers, createStore } from "redux";
import { connect, Provider } from "react-redux";
import thunk from "redux-thunk";
import "./index.css";

// actions.js
const addRepos = repos => ({ type: "ADD_REPOS", repos });
const clearRepos = () => ({ type: "CLEAR_REPOS" });
const getRepos = username => async dispatch => {
  try {
    const url = `https://api.github.com/users/${username}/repos`;
    const response = await fetch(url);
    const responseBody = await response.json();
    dispatch(addRepos(responseBody));
  } catch (error) {
    console.log(error);
    dispatch(clearRepos());
  }
};

// reducers.js
const repos = (state = [], action) => {
  switch (action.type) {
    case "ADD_REPOS":
      return action.repos;
    case "CLEAR_REPOS":
      return [];
    default:
      return state;
  }
};

const store = createStore(repos, applyMiddleware(thunk));

// App.js
function App(props) {
  var textInput;
  var setTextInputRef = element => {
    textInput = element;
  };
  var submit = () => props.getRepos(textInput.value);
  return (
    <div>
      <h1>Enter Github username: </h1>
      <input defaultValue="johnsmith" type="text" ref={setTextInputRef} />
      <button onClick={submit}>Get All Repositories</button>
      <ul>
        {props.repos.map((repo, index) => (
          <li key={index}>
            <a href={repo.html_url}>{repo.name}</a>
          </li>
        ))}
      </ul>
    </div>
  );
}

// AppContainer.js
const mapStateToProps = state => ({ repos: state });

const mapDispatchToProps = { getRepos };
const AppContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

ReactDOM.render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  document.getElementById("root")
);

This is the updated CodeSandbox here.

To retrieve repositories upon loading:

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { applyMiddleware, combineReducers, createStore } from "redux";
import { connect, Provider } from "react-redux";
import thunk from "redux-thunk";
import "./index.css";

// actions.js
const addRepos = repos => ({ type: "ADD_REPOS", repos });
const clearRepos = () => ({ type: "CLEAR_REPOS" });
const getRepos = username => async dispatch => {
  try {
    const url = `https://api.github.com/users/${username}/repos`;
    const response = await fetch(url);
    const responseBody = await response.json();
    dispatch(addRepos(responseBody));
  } catch (error) {
    console.log(error);
    dispatch(clearRepos());
  }
};

// reducers.js
const repos = (state = [], action) => {
  switch (action.type) {
    case "ADD_REPOS":
      return action.repos;
    case "CLEAR_REPOS":
      return [];
    default:
      return state;
  }
};

const store = createStore(repos, applyMiddleware(thunk));

// App.js
class App extends React.Component {
  componentDidMount() {
    this.submit();
  }

  submit = () => this.props.getRepos(this.textInput.value);

  render() {
    return (
      <div>
        <h1>Enter Github username: </h1>
        <input defaultValue="johnsmith" type="text" ref={ref => (this.textInput = ref)} />
        <button onClick={this.submit}>Get All Repositories</button>
        <ul>
          {this.props.repos.map((repo, index) => (
            <li key={index}>
              <a href={repo.html_url}>{repo.name}</a>
            </li>
          ))}
        </ul>
      </div>
    );
  }
}
// AppContainer.js
const mapStateToProps = state => ({ repos: state });

const mapDispatchToProps = { getRepos };
const AppContainer = connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

ReactDOM.render(
  <Provider store={store}>
    <AppContainer />
  </Provider>,
  document.getElementById("root")
);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Struggling to Align NAV buttons to the Right in React Framework

My current Mobile Header view can be seen here: https://i.stack.imgur.com/CcspN.png I am looking to achieve a layout similar to this, https://i.stack.imgur.com/pH15p.png. So far, I have only been able to accomplish this by setting specific left margins, ...

The state update is triggering a soft refresh of the page within Next.js

In my Next.js project, I have integrated a modal component using Radix UI that includes two-way bound inputs with state management. The issue arises when any state is updated, triggering a page-wide re-render and refreshing all states. Here is a snippet of ...

What is the best way to retrieve the state value upon page refresh in React?

Currently, I am working on integrating a time tracker feature into my project. The tracker value is stored in the state when it is started and updated in the state when it is paused. However, upon refreshing the page, I am facing an issue where the last up ...

What are the possible reasons for the failure of Material UI Theme overrides?

I'm having issues with the material UI "createTheme" function. I've added overrides for buttons and switches, but they are not working as expected. Surprisingly, only some features like theme palette and font-size seem to be working properly. Can ...

Utilizing React Native to pass a function to a child component as a prop, with the caveat that `this.props.functionName` is

This query has been floating around in various places, but despite my efforts to bind or declare things differently, I always end up with the same error message stating that _this3.props.toggleProp() is not a function (In '_this3.props.toggleProp()&ap ...

Tips for utilizing two renderCell functions in a datagrid from Material UI without encountering duplication or repetition

Utilizing Material UI, I have designed a table to showcase my data. In this setup, I am required to use renderCell for two specific properties: 'level by user' and 'level by referent'. Issue: The problem arises when Material UI displa ...

Error: The React library component bg-image was missing when utilized in a Next.js application within an Nx monorepository

I am facing an issue with my React library component not finding its background image when used in my Next.js app within the same Nx workspace. The console is showing: localhost:4200/images/svg/Background.svg 404 (Not Found) After hours of searching onli ...

What is the process for retrieving the address of the connected wallet using web3modal?

I've been working on an application using next.js and web3. In order to link the user's wallet to the front-end, I opted for web3modal with the following code: const Home: NextPage = () => { const [signer, setSigner] = useState<JsonRpcSig ...

Enhancing React components with dynamic background colors for unique elements

I am encountering an issue while using a map in my code. Specifically, I want to set the background of a particular element within the map. The element I am referring to is "item .title". I aim for this element to have a background color like this: https:/ ...

How can I eliminate the outline from the modal backdrop using Material UI styling shown in the image provided?

https://i.stack.imgur.com/cBCzd.png After attempting to remove the border and box shadow, I am still encountering issues with lines appearing only when clicking on the modal body. The modal styling code has been omitted as it primarily includes flex styli ...

How does NextJS effectively perform interpolation on the code provided?

I've been curious about the way NextJS distinguishes between JSX and JS in the code snippet below. It seems straightforward, but I'm interested in what's happening behind the scenes. Specifically, I'm puzzled by how JSX is successfully ...

Optimizing the FormControlLabel with the label prop

I'm attempting to nest a RadioGroup inside AccordionDetails, and then add the Accordion list as options within an Autocomplete component in its renderOption props. The issue I'm encountering is that when clicking on the label (which is a span el ...

NPM: There are no valid TypeScript file rules specified

Currently working on a small project using React.JS. Whenever I execute : npm run start, the following message gets logged: Starting type checking and linting service... Using 1 worker with 2048MB memory limit Watching: /Users/John/Projects/myProject/src ...

React: Unusual behavior when re-rendering

Here is an example code sandbox: https://codesandbox.io/s/friendly-lumiere-srnyu?file=/src/App.js In my observation, the console output shows that the state is logged 3 times, with the last log displaying as state:2, version:1. However, the view continues ...

Tips for integrating Stripe into a React test

I am currently conducting a test on a React component that utilizes Stripe, and I am unsure about the best way to structure the test. An error message has been popping up as follows: Error: In order to use react-stripe-elements, ensure that Stripe.js ( ...

I receive a warning when attempting to showcase HTML code generated from a WYSIWYG editor in React

In my React project, I have implemented a WYSIWYG component that saves HTML code to the database. When displaying the saved code in the application, I use the following syntax: import ReactHtmlParser from "react-html-parser"; ... <div classN ...

Checkbox fails to trigger onChange when the checked value is controlled by state management

Currently, I am working with a material-ui Table and have been in the process of implementing multi-select functionality on it. The behavior I am aiming for my multi select to exhibit is as follows: Checkboxes should only appear at the beginning of a ro ...

Transform routeParams from string to numerical format

Currently, I am working on a straightforward project where I need to retrieve data based on the id number using "routeParams". However, I encountered an issue because the "routeParams" is in string format and I actually need it to be converted to a numbe ...

The art of defining PropTypes for the style attribute in Reactjs

Is there a way to pass the 'style' attribute into my component using JSX syntax? <InputTextWithValidation id="name" style={{width:'100%'}} .../> I'm wondering how I should define the PropTypes for ...

Error occurred while trying to launch React application with "npm start" command due to ELIFECYCLE issue

Encountering an error while attempting to launch my React app. events.js:174 throw er; // Unhandled 'error' event ^ Error: spawn powershell.exe ENOENT at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19) ...