#StackBounty: #javascript #reactjs #jestjs #react-testing-library #react-error-boundary How do I test the fallback component for the Er…

Bounty: 100

I have this component:

import React, { lazy, Suspense } from 'react';
import { ErrorBoundary } from '../ErrorBoundary';

const FALLBACK = <svg aria-label="" data-testid="icon-fallback" viewBox="0 0 21 21" />;

const ERROR = (
    <svg data-testid="icon-notdef" viewBox="0 0 21 21">
        <path d="M0.5,0.5v20h20v-20H0.5z M9.1,10.5l-6.6,6.6V3.9L9.1,10.5z M3.9,2.5h13.2l-6.6,6.6L3.9,2.5z M10.5,11.9l6.6,6.6H3.9 L10.5,11.9z M11.9,10.5l6.6-6.6v13.2L11.9,10.5z" />
    </svg>
);

export const Icon = ({ ariaLabel, ariaHidden, name, size }) => {
    const LazyIcon = lazy(() => import(`../../assets/icons/${size}/${name}.svg`));
    return (
        <i aria-hidden={ ariaHidden }>
            <ErrorBoundary fallback={ ERROR }>
                <Suspense fallback={ FALLBACK }>
                    <LazyIcon aria-label={ ariaLabel } data-testid="icon-module" />
                </Suspense>
            </ErrorBoundary>
        </i>
    );
};

I’m trying to test the condition where an SVG is passed in that doesn’t exist, in turn rendering the <ErrorBoundary /> fallback. The ErrorBoundary works in the browser, but not in my test.

This is the failing test:

test('shows notdef icon', async () => {
    const { getByTestId } = render(<Icon name='doesnt-exist' />);
    const iconModule = await waitFor(() => getByTestId('icon-notdef'));
    expect(iconModule).toBeInTheDocument();
});

I get this error message:

TestingLibraryElementError: Unable to find an element by: [data-testid="icon-notdef"]”.

How do I access ErrorBoundary fallback UI in my test?

Edit

This is the code for the <ErrorBoundary /> component:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

export class ErrorBoundary extends Component {
    constructor(props) {
        super(props);
        this.state = {
            error: '',
            errorInfo: '',
            hasError: false,
        };
    }

    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }

    componentDidCatch(error, errorInfo) {
        console.error({ error, errorInfo });
        this.setState({ error, errorInfo });
    }

    render() {
        const { children, fallback } = this.props;
        const { error, errorInfo, hasError } = this.state;

        // If there is an error AND a fallback UI is passed in…
        if (hasError && fallback) {
            return fallback;
        }

        // Otherwise if there is an error with no fallback UI…
        if (hasError) {
            return (
                <details className="error-details">
                    <summary>There was an error.</summary>
                    <p style={ { margin: '12px 0 0' } }>{error && error.message}</p>
                    <pre>
                        <code>
                            {errorInfo && errorInfo.componentStack.toString()}
                        </code>
                    </pre>
                </details>
            );
        }

        // Finally, render the children.
        return children;
    }
}

ErrorBoundary.propTypes = {
    children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]).isRequired,
    fallback: PropTypes.node,
};

… and this is the full error with DOM that I get for the test:

shows notdef icon

    TestingLibraryElementError: Unable to find an element by: [data-testid="icon-notdef"]

    <body>
      <div>
        <i
          aria-hidden="false"
          class="Icon Icon--sm"
        >
          <span
            aria-label=""
            data-testid="icon-module"
          />
        </i>
      </div>
    </body>

    <html>
      <head />
      <body>
        <div>
          <i
            aria-hidden="false"
            class="Icon Icon--sm"
          >
            <span
              aria-label=""
              data-testid="icon-module"
            />
          </i>
        </div>
      </body>
    </html>Error: Unable to find an element by: [data-testid="icon-notdef"]

Lastly, my SVG mock:

import React from 'react';

const SvgrMock = React.forwardRef(
    function mySVG(props, ref) {
        return <span { ...props } ref={ ref } />;
    },
);

export const ReactComponent = SvgrMock;
export default SvgrMock;


Get this bounty!!!

#StackBounty: #javascript #reactjs How to load custom script in react?

Bounty: 50

This is somewhat similar to this question:

Adding script tag to React/JSX

But in my case I am loading a script like this:

<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','ID');</script>
<!-- End Google Tag Manager -->

Now I know there is a npm package for the google tag manager but I am curious if I would like to do this in a custom way how would I go about?

In the above question I see a lot of:

const script = document.createElement("script");

script.src = "https://use.typekit.net/foobar.js";
script.async = true;

document.body.appendChild(script);

Which is fine but if I have a function inside of the loaded script how would I go about executing this correctly?


Get this bounty!!!

#StackBounty: #javascript #reactjs #django #heroku Error when deplyoing Django-React app to Heroku

Bounty: 50

I’m deploying my Django-backend, React-frontend app to Heroku and when running git push heroku master I’m running into a weird error:

Could not find a required file.
Name: index.html Searched in:
/tmp/build_7abd977a/public

Apparently when running npm run build it creates a build folder with the following structure:

enter image description here

Looks like for some reason the public folder isn’t created upon running the scripts, can someone advice how can I perhaps create it with the script or run my index.html from a different location (Or at least the location of the file its being imported in)?

Here is the full traceback:

enter image description here


Get this bounty!!!

#StackBounty: #javascript #reactjs #redux #ecmascript-6 #react-redux How to add protected routes in react redux

Bounty: 250

I have created a login component on which I have all the logic stuff.

The login reducer is:

const openState = {
  loggedIn: null,
  user: null
}

export default (state = openState, action) => {
  switch (action.type) {
    case LOGIN:
      return { ...state, loggedIn: true, user: action.payload }
    case LOGOUT:
      return { ...state, loggedIn: false, user: null }
    default:
      return openState
  }
}

The Action :

export const logIn = (user) => {
  return {
    type: LOGIN,
    payload: user
  }
}

export const logOut = () => {
  return {
    type: LOGOUT
  }
}

everything is working just fine but I’m not sure how to pass the loggedIn and user props from action into the routes component in order to secure all routes:

const MainRoutes = props => {
  const { loggedIn } = props;

  console.log(props.loggedIn)

return (
  <Router history={history}>
    <Baseline />
    <Menu/>
    <Container maxWidth="md">
      <Switch>
        <Route exact path="/Login" component={Login} />
        <Route exact path="/Carousel" component={Carousel} />
        <Route exact path="/Stepper" component={Stepper} />
        <Route component={NotFound} />
      </Switch>
    </Container>
  </Router>
);
}

const mapStateToProps = (state) => {
return { loggedIn: state.loggedIn };
};

export default connect(mapStateToProps)(MainRoutes);

If I’ll console.log the loggedIn props I get undefined 😐
Based on loggedIn I can create a logic into the routes component.


Get this bounty!!!

#StackBounty: #javascript #css #reactjs #twitter-bootstrap Trying to emulate Bootstrap navbar collapse/expand with React State

Bounty: 100

I am trying to use Bootstrap to expand and collapse the navbar when the hamburger icon is clicked. The issue is I am using React and I’m pretty sure Bootstrap’s DOM manipulation is conflicting with React’s DOM manipulation. So I’m trying to pull all the manipulation away from Bootstrap and rely purely on their styling and use React to update the classes instead. That feels like the correct way to me. Now I realize things like React Bootstrap exist but I already have vanilla Bootstrap integrated throughout my project and it appears like React Bootstrap is still on version 4, where I am using 5.

So as far as I can tell, Bootstrap is manipulating the classes on this div: <div id="navbarSupportedContent" style="" class="navbar-collapse collapse">. So it appears that they are adding the class collapsing and removing the class collapse as the menu is expanding or collapsing. And then once it is fully shown, classes become navbar-collapse collapse show and for collapsed: navbar-collapse collapse.

The transition time is set to .35 seconds by Bootstrap. So here is my React code:

const handleNavCollapse = () => {
        if (isNavCollapsed) {
            setNavbarClasses('navbar-collapse collapsing');
            //setTimeout(  <-- I learned this way does not work correctly
            setTimeout(() => 
                setNavbarClasses('navbar-collapse collapse show'),
                350
            );
        } else {
            setNavbarClasses('navbar-collapse collapse');
        }
        setIsNavCollapsed(!isNavCollapsed);
    };

Also, if this helps someone figure out an answer, here is the CSS that Bootstrap is applying with the collapsing class:

.collapsing {
    height: 0;
    overflow: hidden;
    transition: height 0.35s ease;
}

It works halfway in that it shows and hides the navbar menu correctly when clicking the hamburger icon. But there is no transition. I’m not seeing the collapsing class get added when I watch the DOM in the inspector like I do on the Bootstrap site. I only see it add show and remove show. Maybe I’m not doing the setTimeout right.

Update: So I figured out from this SO answer: https://stackoverflow.com/a/42650143/571723 that I was in fact doing the setTimeout wrong. I switched to the arrow function. And now I see the collapsing class getting added right away and then switching to show after the 350ms timeout. Problem is there is still no transition animation, it merely shows the menu after 350ms.

Update 2: I’m getting further with my investigation into how Bootstrap is doing this. I have managed to take a screenshot of the console while Bootstrap was animating the navbar on their site.
enter image description here
So you can see the height set to a specific number and that changes very quickly (actually that number does not change, it gets set to the 206px and stays there until it is fully opened). And you can also see height: 0 being overridden. Those things are not happening in my site in the inspector.


Get this bounty!!!

#StackBounty: #javascript #reactjs #axios #react-select #react-hook-form How to have conditional defaultValues from useEffect in react-…

Bounty: 50

I’m working on a form using react-hook-form that contains a react-select CreatableSelect multiselect input. The multiselect is used for tags of a given post and it is conditional based on if the user selects to update the tags of an existing post.

My issue is that the defaultValue for the multiselect is not working when a user selects an existing post that contains tags.

The overall flow is: User selects existing post (in PublicShareNetworkSelect in my example) > onChange function changes the post ID stored in hook (selectedNetwork in my example) > change in selectedNetwork fires getNetworkData function that sets the tags variable (networkTags) used as the multiselect defaultValue

Also the getTags() function is used to populate the options in the multiselect.

I believe that the issue as something to do with getting the data from the APIs because I tried to create a minimum reproducible example, but it works exactly how I want it to without the axios calls. However, when I console.log the allTags and networkTags in my full example, there are matching objects in the arrays (the matches should be the defaultValue).

Code example: Main/Parent form component

import React, { useState, useEffect } from "react";
import axios from "axios";
import Form from "react-bootstrap/Form";
import { useForm, Controller } from "react-hook-form";
import CreatableSelect from "react-select/creatable";
import Button from "react-bootstrap/Button";
import PublicShareNetworkSelect from "./publicShareNetworkSelect";

function PublicShareForm(props) {
  const {
    register,
    handleSubmit,
    reset,
    control,
    errors,
    watch,
    onChange,
  } = useForm();
  const [loading, setLoading] = useState(false);
  const [selectedNetwork, setSelectedNetwork] = useState([]);
  const [allTags, setAllTags] = useState();
  const [networkTags, setNetworkTags] = useState([]);

  //Create axios instance
  const axiosSharedNetwork = axios.create();

  async function getTags() {
    const getAllTagsApi = {
      url: "/public-share/get-all-tags",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json;charset=UTF-8",
      },
      method: "GET",
    };
    await axiosSharedNetwork(getAllTagsApi)
      .then((response) => {
        const resData = response.data;
        const tags = resData.map((tag, index) => ({
          key: index,
          value: tag.tag_id,
          label: tag.name,
        }));
        setAllTags(tags);
        setLoading(false);
      })
      .catch((error) => {
        console.log(error.response);
      });
  }

  async function getNetworkData(networkId) {
    const getNetworkDataApi = {
      url: "/public-share/get-network/" + networkId,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json;charset=UTF-8",
      },
      method: "GET",
    };
    const getNetworkTagsApi = {
      url: "/public-share/get-network-tags/" + networkId,
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json;charset=UTF-8",
      },
      method: "GET",
    };
    await axiosSharedNetwork(getNetworkDataApi)
      .then(async (response) => {
        const resData = response.data;
        //Set some variables (i.e. title, description)
        await axiosSharedNetwork(getNetworkTagsApi)
          .then(async (response) => {
            const tagResData = response.data;
            const tags = tagResData.map((tag, index) => ({
              key: index,
              value: tag.tag_id,
              label: tag.name,
            }));
            setNetworkTags(tags);
            setLoading(false);
          })
          .catch((error) => {
            console.log(error.response);
          });
      })
      .catch((error) => {
        console.log(error.response);
      });
  }

  useEffect(() => {
    getTags();
    getNetworkData(selectedNetwork);
  }, []);

  async function onSubmit(data) {
    //Handle submit stuff
  }
  console.log(allTags);
  console.log(networkTags);
  return (
    <Form id="public-share-form" onSubmit={handleSubmit(onSubmit)}>
      <Form.Group>
        <Form.Label>Create New Version of Existing Shared Network?</Form.Label>
        <PublicShareNetworkSelect
          control={control}
          onChange={onChange}
          setSelectedNetwork={setSelectedNetwork}
        />
        <Form.Label>Tags</Form.Label>
        <Controller
          name="tags"
          defaultValue={networkTags}
          control={control}
          render={({ onChange }) => (
            <CreatableSelect
              isMulti
              placeholder={"Select existing or create new..."}
              onChange={(e) => onChange(e)}
              options={allTags}
              defaultValue={networkTags}
              classNamePrefix="select"
            />
          )}
        />
      </Form.Group>
        <Button variant="secondary" onClick={props.handleClose}>
          Cancel
        </Button>
        <Button variant="primary" type="submit">
          Share
        </Button>
    </Form>
  );
}

export default PublicShareForm;

PublicShareNetworkSelect – the select component that triggers the function to set the existing post id (selectedNetwork):

import React, { useState, useEffect } from "react";
import axios from "axios";
import { Controller } from "react-hook-form";
import Select from "react-select";

function PublicShareNetworkSelect(props) {
  const [loading, setLoading] = useState(false);
  const [networks, setNetworks] = useState([]);
  //Create axios instance
  const axiosNetworks = axios.create();
  // Add a request interceptor
  axiosNetworks.interceptors.request.use(
    function (config) {
      // Do something before request is sent
      setLoading(true);
      return config;
    },
    function (error) {
      // Do something with request error
      setLoading(false);
      return Promise.reject(error);
    }
  );

  // Add a response interceptor
  axiosNetworks.interceptors.response.use(
    function (response) {
      // Any status code that lie within the range of 2xx cause this function to trigger
      // Do something with response data
      setLoading(true);
      return response;
    },
    function (error) {
      // Any status codes that falls outside the range of 2xx cause this function to trigger
      // Do something with response error
      setLoading(false);
      return Promise.reject(error);
    }
  );

  async function getNetworks() {
    const getNetworksApi = {
      url: "public-share/get-user-networks/" + props.username,
      method: "GET",
    };
    await axiosNetworks(getNetworksApi)
      .then(async (response) => {
        setNetworks(
          response.data.map((network, index) => ({
            key: index,
            value: network.network_id,
            label: network.title,
          }))
        );
        setLoading(false);
      })
      .catch((error) => {
        console.log(error.response);
      });
  }

  useEffect(() => {
    getNetworks();
  }, []);

  function handleChange(data) {
    console.log(data);
    if (data) {
      props.setSelectedNetwork(data.value);
      props.getNetworkData(data.value);
    } else {
      props.setNetworkTitle("");
      props.setNetworkDesc("");
    }
  }

  if (!loading) {
    if (networks.length === 0) {
      return (
        <React.Fragment>
          <br />
          <p className="font-italic text-muted">
            You haven't created any public networks yet.
          </p>
        </React.Fragment>
      );
    } else {
      return (
        <Controller
          name="network"
          defaultValue={""}
          control={props.control}
          render={({ onChange }) => (
            <Select
              closeMenuOnSelect={true}
              isClearable={true}
              options={networks}
              noOptionsMessage={() => "No matching options"}
              defaultValue={""}
              onChange={(e) => handleChange(e)}
              className="basic-single"
              classNamePrefix="select"
            />
          )}
        />
      );
    }
  } else {
    return <React.Fragment>Loading...</React.Fragment>;
  }
}

export default PublicShareNetworkSelect;

Edit 1: console.log output for allTags (options) and networkTags (defaultValue)
enter image description here


Get this bounty!!!

#StackBounty: #javascript #reactjs #build #react-table React table Gives empty table in build

Bounty: 50

This is a very strange issue but I was using react-table 7.0.0.rc16 and I recently upgraded to react-table 7.0.1 the problem is my data works in dev mode but as soon I create a react build it wont render anything I would like to know why and I am attaching my package.json for the same.
sandbox

Demo

Package.json

{
  "name": "test",
  "homepage": "http://www.test.com",
  "version": "0.0.0",
  "private": true,
  "dependencies": {
    "@date-io/date-fns": "^1.3.11",
    "@material-ui/core": "^4.4.2",
    "@material-ui/icons": "^4.4.3",
    "@material-ui/lab": "^4.0.0-alpha.39",
    "@material-ui/pickers": "^3.2.6",
    "bootstrap": "^4.4.1",
    "classnames": "^2.2.6",
    "date-fns": "^2.9.0",
    "echarts": "4.2.1",
    "echarts-for-react": "^2.0.15-beta.0",
    "formik": "^1.5.8",
    "formik-material-ui": "^0.0.22",
    "google-map-react": "^1.1.5",
    "i18next": "^17.0.18",
    "i18next-browser-languagedetector": "^4.0.0",
    "i18next-xhr-backend": "^3.2.0",
    "immutable": "^4.0.0-rc.12",
    "node-sass": "^4.12.0",
    "prop-types": "^15.6.1",
    "react": "^16.9.0",
    "react-csv": "^2.0.3",
    "react-custom-scrollbars": "^4.2.1",
    "react-d3-tree": "^1.16.1",
    "react-dom": "^16.9.0",
    "react-google-maps": "^9.4.5",
    "react-i18next": "^10.13.1",
    "react-redux": "^7.1.1",
    "react-router-dom": "^5.1.2",
    "react-scripts": "^2.0.3",
    "react-table": "7.0.1",
    "redux": "^4.0.4",
    "redux-saga": "^1.1.3",
    "yup": "^0.27.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "watch": "react-scripts start --watch",
    "build": "CI=false react-scripts --expose-gc --max-old-space-size=4096 build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject",
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build"
  },
  "devDependencies": {
    "eslint-config-prettier": "^6.4.0",
    "eslint-plugin-prettier": "^3.1.1",
    "prettier": "^1.18.2"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

Package-lock.json is also attached as a file
image of table image of table when doing prod build

I am using node v10.23.1 and npm 6.14.10.


Get this bounty!!!

#StackBounty: #reactjs #react-router-dom #server-side-rendering React SSR Client React Router Dom Switch "Invariant Failed"

Bounty: 50

SSR/Client React Router Dom "Switch" breaks for me with a "Invariant Failed". I believe it says it has something to do with Switch not been allowed outside "Router", which it isn’t.

The minimal project link is below, that may be easier way look at the project. I have listed the main files below

1: SERVER SIDE RENDER ENDPOINT

// EXPRESS ROUTER
const express = require("express");
const aRouter = express.Router();

// REACT UTILITIES
import React from "react";
import { renderToNodeStream } from "react-dom/server";
import { StaticRouter } from "react-router-dom";
import { createMemoryHistory } from "history";
import Loadable from "react-loadable";

// REDUX UTILITIES
import { init } from "../src/module/store";
import { Provider } from "react-redux";

// CUSTOM COMPONENTS
import App from "../src/App";

// UTILITIES
import fs from "fs-extra";
import renderUtils from "../utils/renderUtils";

// ASSETS
import { initState } from "../assets/store/init";

aRouter.get(["/", "/home"], async function (req, res) {

  console.log("RENDER HOME");

  try {

    // INITIAL WRITE TO CLIENT - START HEAD
    res.setHeader('Content-Type', 'text/html');
    res.write("<!DOCTYPE html>");
    res.write("<html style='scrollbar-width: none;'>");

    let headHTML = await fs.readFile("./public/head.html", "utf-8");
    let scriptsHTML = await fs.readFile("./public/scripts.html", "utf-8");

    res.write(headHTML);
    res.write("<body>");
    res.write(`<div id = "app-container">`);

    // INITALISING STATE
    var initialState = initState();
    initialState.article.articles = {
      "abcde": {
        title: "My First Article",
        body: "This is my first article"
      },
      "fghij": {
        title: "My Second Article",
        body: "This is my second article"
      },
      "klmno": {
        title: "My Third Article",
        body: "This is my third article"
      }
    };
    initialState.article.fetched = true;
    initialState.ui.user = { type: "" };
    initialState.ui.global = {
      team: "Arsenal",
      teamID: 19
    };

    const history = createMemoryHistory({ initialEntries: [req.originalUrl] });
    const store = init(history, initialState);
    
    // THE ISSUE SEEMS TO BE TO DO WITH THIS SERVER SIDE STATIC BROWSER AND THE CLIENT BORWSER ROUTER
    const stream = renderToNodeStream(
      <Provider store = {store}>
        <StaticRouter history = {history} location = {req.originalUrl} context = {{}}>
          <App />
        </StaticRouter>
      </Provider>
    );

    stream.pipe(res, { end: false });
    stream.on("end", renderUtils.onRenderEnd.bind(this, res, store, scriptsHTML));

  } catch (err) { renderUtils.onRenderError.bind(this, res, "RENDER HOME ERROR", err.message); }

});

var self = (module.exports = aRouter);

2: CLIENT INDEX

// REACT
import React from "react";
import ReactDOM from "react-dom";
import Loadable from "react-loadable";
import { BrowserRouter } from "react-router-dom";
import { createMemoryHistory } from "history";
import { Provider } from "react-redux";

// REDUX
import { init } from "./module/store";

// CREATE STORE
let history = createMemoryHistory();
let store = init(history, window.INITIAL_STATE);

// MAIN APP COMPONENT
import App from "./App";

// MOUNTED STYLES
import "./style/client/index.scss";

const renderApp = () => {
  ReactDOM.hydrate(
    <Provider store = {store}>
      <BrowserRouter history = {history}>
        <App />
      </BrowserRouter>
    </Provider>,
    document.getElementById("app-container")
  );
};

store.subscribe(() => renderApp());

3: APP – CLIENT

// REACT
import React, { PureComponent } from "react";
import { Switch, Route } from "react-router-dom";
import PropTypes from "prop-types";

// REDUX STORE
import { connect } from "react-redux";
import { getName, getAge, getPosition } from "./module/user/userReducer";
import { getUIElement, setUIElement } from "./module/uiReducer";

// IMPORT CUSTOM COMPONENTS
import Routes from "./Routes";

class App extends PureComponent {

  componentDidMount = () => this.props.setUI("user", "type", "admin");

  render = () => {
    return (
      <div className = "app">
        <span>My App</span>
        <span>Name : {this.props.name}</span>
        <span>Age : {this.props.age}</span>
        <span>Position : {this.props.position}</span>
        <span>Team : {this.props.team}</span>
        <span>Team ID : {this.props.teamID}</span>
        <span>Type : {this.props.type}</span>
        <div>
          <Switch>
            <Route path = "/" component = {MyLocation} />
            <Route path = "/contact" render = {() => (<MyLocation location = "Contact" />)} />
          </Switch>
        </div>
      </div>
    );
  };

};

App.propTypes = {
  name: PropTypes.string.isRequired,
  age: PropTypes.number.isRequired,
  position: PropTypes.string.isRequired,
  team: PropTypes.string.isRequired,
  teamID: PropTypes.number.isRequired,
  type: PropTypes.string.isRequired,
  setUI: PropTypes.func.isRequired
};

const mapStateToProps = state => ({
  name: getName(state),
  age: getAge(state),
  position: getPosition(state),
  team: getUIElement(state, "global", "team"),
  teamID: getUIElement(state, "global", "teamID"),
  type: getUIElement(state, "user", "type")
});

const mapDispatchToProps = dispatch => ({
  setUI: (component, element, value) => dispatch(setUIElement({ component, element, value }))
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

The full minimal react app here

It just breaks when I add the Switch and Routes. The Switch "IS INSIDE" the Browser Router. I have read articles which explain to send the same React Router Dom to the client, but I tried them explanations and they dont work for me.

To run the project simply run "yarn", "npm run build" and "npm start". The app has just one page with some filler text

Issue : Breaks at Switch
Required: Work at Switch
Tried: Explantions that explain to bring same instance of react-router-dom to client from server and use webpack alies etc.

Whats also funny is this works live on Heroku "production", but doesnt work locally "production". Im thinking heroku have some fallback code catching it.

Any help be great;

Daniel


Get this bounty!!!

#StackBounty: #javascript #reactjs #react-native #expo #react-native-ios Native Module cannot be null (ios) – Expo

Bounty: 100

I am developing a Expo-managed (not bare) mobile application. I recently ran into this issue: it crashes on start on ios. and I understand that this has to do with some of my packages requiring ios native modules, therefor I have to eject before I can use this package.

However, my goal here is not to eject but to find the package causing this issue, however, unable find it so far.

What suprises me is that android runs without issues, even though it looks like it requires native modules.

Please note everything runs fine on android

Error
enter image description here

package.json

{
  "main": "node_modules/expo/AppEntry.js",
  "scripts": {
    "start": "expo start",
    "android": "expo start --android",
    "ios": "expo start --ios",
    "web": "expo start --web",
    "eject": "expo eject",
    "test": "jest --watchAll"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "@expo/vector-icons": "^12.0.0",
    "@microsoft/signalr": "^3.1.9",
    "@react-native-community/async-storage": "~1.12.0",
    "@react-native-community/datetimepicker": "3.0.4",
    "@react-native-community/masked-view": "0.1.10",
    "@react-navigation/bottom-tabs": "^5.9.2",
    "@react-navigation/native": "^5.7.6",
    "@react-navigation/stack": "^5.9.3",
    "expo": "^40.0.0",
    "expo-asset": "~8.2.1",
    "expo-av": "~8.7.0",
    "expo-camera": "~9.1.0",
    "expo-constants": "~9.3.3",
    "expo-document-picker": "~8.4.1",
    "expo-file-system": "~9.3.0",
    "expo-font": "~8.4.0",
    "expo-image-manipulator": "~8.4.0",
    "expo-image-picker": "~9.2.0",
    "expo-linking": "~2.0.0",
    "expo-media-library": "~10.0.0",
    "expo-notifications": "~0.8.2",
    "expo-splash-screen": "~0.8.1",
    "expo-status-bar": "~1.0.3",
    "expo-web-browser": "~8.6.0",
    "i": "^0.3.6",
    "install": "^0.13.0",
    "jwt-decode": "^3.0.0",
    "moment": "^2.29.1",
    "npm": "^6.14.9",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-native": "https://github.com/expo/react-native/archive/sdk-40.0.1.tar.gz",
    "react-native-app-intro-slider": "^4.0.4",
    "react-native-audio-record": "^0.2.2",
    "react-native-country-picker-modal": "^2.0.0",
    "react-native-datepicker": "^1.7.2",
    "react-native-gesture-handler": "~1.8.0",
    "react-native-image-view": "^2.1.9",
    "react-native-image-zoom-viewer": "^3.0.1",
    "react-native-modal-datetime-picker": "^9.0.0",
    "react-native-paper": "^4.2.0",
    "react-native-safe-area-context": "3.1.9",
    "react-native-screens": "~2.15.0",
    "react-native-spinkit": "^1.5.1",
    "react-native-status-bar-height": "^2.5.0",
    "react-native-toast-message": "^1.3.4",
    "react-native-web": "~0.13.12",
    "react-navigation": "^4.4.3",
    "react-navigation-material-bottom-tabs": "^2.3.3"
  },
  "devDependencies": {
    "@babel/core": "~7.9.0",
    "@types/react": "~16.9.35",
    "@types/react-native": "~0.63.2",
    "babel-preset-expo": "8.3.0",
    "jest-expo": "^40.0.0",
    "typescript": "~4.0.0"
  },
  "private": true
}


Get this bounty!!!

#StackBounty: #javascript #reactjs #axios Disabling the preloader after the data appears on the website

Bounty: 50

How can I set the preloader in axios.interceptor to turn off how will the data be displayed on the page? At this point, I can see the data is downloaded, the preloader turn off and I can see the jump as the data appears on the page. Intended effect: disabling the preloader when data appears on the website.

Example: https://stackblitz.com/edit/react-ca6osn?file=src%2FApp.js

Axios.interceptors.request.use(function (config) {

  // spinning start to show
  // UPDATE: Add this code to show global loading indicator
  document.body.classList.add('loading-indicator');

  return config
}, function (error) {
  return Promise.reject(error);
});

Axios.interceptors.response.use(function (response) {

  // spinning hide
  // UPDATE: Add this code to hide global loading indicator
  document.body.classList.remove('loading-indicator');

  return response;
}, function (error) {
  return Promise.reject(error);
});

export default function App() {
  const [values, setValues] = useState({
        title: []
    });

  useEffect(() => {
    loadProfile();
    }, []);


    const loadProfile = () => { 

        axios({
            method: 'GET',
            url: `https://jsonplaceholder.typicode.com/todos`,
          })
          .then(res => {

        setValues({...values, title: res.data});
          })
          .catch(err => {
        console.log('error', err.response.data);
      
          })
  }

  return (
    
    <div>
       {values.title.map(data => (
          <div style={{ border: "1px black solid" }}>
            <p>{data.title}</p>
          </div>
      ))}
    </div>
  );
}

CSS

.loading-indicator:before {
    content: '';
    background: black;
    position: fixed;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    z-index: 1000;
}

.loading-indicator:after {
    content: 'Loading';
    position: fixed;
    width: 100%;
    top: 50%;
    left: 0;
    z-index: 1001;
    color:white;
    text-align:center;
    font-weight:bold;
    font-size:1.5rem;        
}


Get this bounty!!!