Categories
discuss

ESLint turn off semicolon rule

When I search for turning off semicolon, I get "semi": 0 or similar I tried to putting it, but still my linter puts semicolon on lines.

Below is my .eslintrc and I am perplexed which rule is putting semicolon.

{
  "parserOptions": {
    "ecmaVersion": 8,
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true,
      "jsx": true
    },
    "sourceType": "module"
  },

  "plugins": [
    "react"
  ],

  "rules": {
    "jsx-quotes": ["error", "prefer-single"],
    "react/jsx-boolean-value": "error",
    "react/jsx-curly-spacing": ["error", "never"],
    "react/jsx-equals-spacing": ["error", "never"],
    "react/jsx-indent": ["error", 2],
    "react/jsx-indent-props": ["error", 2],
    "react/jsx-no-duplicate-props": "error",
    "react/jsx-no-undef": "error",
    "react/jsx-tag-spacing": ["error", { "beforeSelfClosing": "always" }],
    "react/jsx-uses-react": "error",
    "react/jsx-uses-vars": "error",
    "react/self-closing-comp": "error",
    "no-console": 0,
    "semi": 0
  }
}

Answer

Try to add this rule: “semi”: [ “error”, “never” ]

If still not fixed, the problem may be that prettier(if you installed) or editor is controlling it.

Go at vscode settings and add

"eslint.autoFixOnSave": true,
Categories
discuss

Flutter Cache JSON response using http response header

I’m trying to create and use a cache for a server JSON response.

something like volley response caching does. https://stackoverflow.com/a/32022946/1993001 in Android

I am using DIO for network operations.

Answer

You can you create your own cache with Interceptors on top of Dio requests.

You can create in on your own:

import 'package:dio/dio.dart';

class CacheInterceptor extends Interceptor {
  CacheInterceptor();

  var _cache = new Map<Uri, Response>();

  @override
  onRequest(RequestOptions options) async {
    return options;
  }

  @override
  onResponse(Response response) async {
    _cache[response.request.uri] = response;
  }

  @override
  onError(DioError e) async{
    print('onError: $e');
    if (e.type == DioErrorType.CONNECT_TIMEOUT || e.type == DioErrorType.DEFAULT) {
      var cachedResponse = _cache[e.request.uri];
      if (cachedResponse != null) {
        return cachedResponse;
      }
    }
    return e;
  }
}

and then use it with:

final dio = Dio()..interceptors.add(CacheInterceptor());   

or just check the library: https://pub.dev/packages/dio_cache

Categories
discuss

‘await’ has no effect on the type of this expression when using await inside an if block

In my code I have an array of user names. I’m trying to go through each name, check whether the user exist in the database and create the user. The problem is, my linter is saying 'await' has no effect on the type of this expression in the places I have marked:

await Promise.all(
  userNames.map(async userName => {
    const user = await users.findOne({ name: userNames });

    if (!user)
      await users.create({ // Linter marks this bracket (Not the curly bracket)
        name: userName,
      }); // And this end bracket
  }),
);

My editor suggests something like this:

  if (user) {
    return;
  }
  await users.create({
    name: userName,
  });

Flipping the if else. Any idea why?

Answer

The issue was, users.create is not a promise to be awaited! One good way to find this is to click on ctrl + click on the method and check it’s type definitions.

Categories
discuss

Redirect with React Functional Components

I am in need of help, I am coding this form and after I submit it, the state for “posted” changes from false to true and I would expect “return Redirect to=”/landing” ;” to redirect me to the landing page, however, it doesn’t which I assume is because the line doesn’t re-run after the initial render. I was hoping that changing the state of “posted” would cause a re-render. I have heard about using history push and tried to adapt it to my code yet I failed. I don’t know how to wrap my component with “withRouter” given that I have it already wrapped with “connect”. How can I achieve this? I have read numerous posts about this yet I can’t figure how to adapt it to my code. Any help is appreciated.

import React, { useState } from "react";
import Navbar from "./Navbar";
import { connect, useDispatch } from "react-redux";
import { Redirect } from "react-router-dom";
import { createProject } from "../actions/projectAction";
import PropTypes from "prop-types";
import { push } from "connected-react-router";

const EditProject = ({ posted, createProject }) => {
  const dispatch = useDispatch();
  const [formData, setFormData] = useState({
    projectTitle: "",
    projectDescription: "",
    deliveryDate: ""
  });

  const { projectTitle, projectDescription, deliveryDate } = formData;

  const onChange = e => {
    setFormData({ ...formData, [e.target.name]: e.target.value });
  };

  const onSubmit = async e => {
    e.preventDefault();
    createProject({ projectTitle, projectDescription, deliveryDate });
    dispatch(push("/login"));
  };

  if (posted) {
    return <Redirect to="/landing" />;
  }

  return (
    <div>
      <Navbar />
      <div className="container">
        <form onSubmit={e => onSubmit(e)}>
          <h4>Project Title</h4>
          <input
            name="projectTitle"
            value={projectTitle}
            className="form-control"
            placeholder="Your project title"
            onChange={e => onChange(e)}
          />
          <h4>Delivery Date</h4>
          <input
            type="date"
            className="form-control"
            name="deliveryDate"
            value={deliveryDate}
            onChange={e => onChange(e)}
          />
          <h4>Description</h4>
          <textarea
            name="projectDescription"
            value={projectDescription}
            className="form-control"
            rows="10"
            onChange={e => onChange(e)}
          ></textarea>
          <input type="submit" className="btn btn-primary" value="Create" />
          <a href="/projects" className="btn btn-danger">
            Cancel
          </a>
        </form>
      </div>
    </div>
  );
};

EditProject.propTypes = {
  createProject: PropTypes.func.isRequired
};

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

export default connect(mapStateToProps, { createProject })(EditProject);

Answer

I think you have to define your route. From my following code you can get a little bit idea of the routing.

In App.js basically I defined the routes and I have created two more functional components Landing and EditProject to simulate your idea. Moreover I have used Link for navigation purpose

App.js

import React, { Component } from "react";
import { BrowserRouter, Route, Switch, Link } from "react-router-dom";
import EditProject from "./editProject";
import Landing from "./landing";

class App extends Component {
  render() {
    return (
      <BrowserRouter>
        <div id="container">
          <div>
            <Link to="/">Landing Page</Link>
            <Link to="/editproject">Edit Project</Link>
          </div>
          <Switch>
            <Route path="/editproject" component={EditProject} />
            <Route exact path="/" component={Landing} />
          </Switch>
        </div>
      </BrowserRouter>
    );
  }
}

export default App;

Landing functional component

import React from "react";

const Landing = () => {
  return <h1>Landing Page</h1>;
};

export default Landing;

EditProject functional component

import React from "react";

const EditProject = props => {
  function handleSubmit(e) {
    e.preventDefault();
    console.log("submitted");
    //do your task here before redirect
    //...
    props.history.push("/");
  }

  return (
    <div>
      <h1>Edit Project</h1>
      <form onSubmit={handleSubmit}>
        <button>Submit</button>
      </form>
    </div>
  );
};

export default EditProject;

Hope it will help you.

Categories
discuss

Typescript debounce function not calling function passed as parameter

I’m trying to write a debounce function with typescript.

I found an example of it in here. Code follows:

export function debounce<Params extends any[]>(
  func: (...args: Params) => any,
  timeout: number,
): (...args: Params) => void {
  let timer: NodeJS.Timeout
  return (...args: Params) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}

Problem is:

  • Function passed as a parameter is not getting called after the specified timeout
  • I can’t use lodash or any other external library because I’m trying to avoid adding new dependencies to this project.

Thanks.

Answer

How do you use your debounce function? I prepare fiddle, you can check working solution here

function debounce<Params extends any[]>(
  func: (...args: Params) => any,
  timeout: number,
): (...args: Params) => void {
  let timer: NodeJS.Timeout
  return (...args: Params) => {
    clearTimeout(timer)
    timer = setTimeout(() => {
      func(...args)
    }, timeout)
  }
}

function test(message) {
  alert(message);
}

const debouncedTest = debounce(test, 2000);

debouncedTest('message');

Well, it’s not typescript troubles

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..