Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
664 views
in Technique[技术] by (71.8m points)

reactjs - Set interval gets clear on browser refresh in my react application

I am using the setInterval function to do an API call to get refresh token after some interval. Every time if I refresh the browser setInterval timer gets clear and starts counting from zero. My access token gets expired and the refresh token never getting a call and user logged out. Is there any way to deal with this?

useEffect(() => {
  const interval = setInterval(() => { 
    setTokenByReSendingAuth(); //dispatch action
  }, 300000);

  return () => clearInterval(interval);
}, [setTokenByReSendingAuth]);
question from:https://stackoverflow.com/questions/65867434/set-interval-gets-clear-on-browser-refresh-in-my-react-application

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Using MERN:

Heres your dependencies:

jwt-decode: https://www.npmjs.com/package/jwt-decode

passport-jwt: http://www.passportjs.org/packages/passport-jwt/

passport: https://www.npmjs.com/package/passport

jsonwebtoken: https://www.npmjs.com/package/jsonwebtoken

bcryptjs: https://www.npmjs.com/package/bcryptjs

Create an express server.js like this:

const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const path = require("path");
const passport = require("passport");
const db = require("./config/.env").mongoURI; //uri in .env file

const app = express();
const port = process.env.PORT || 5000;

app.use(cors());
app.use(express.json());

mongoose.connect(db, {
  useNewUrlParser: true,
  useCreateIndex: true,
  useUnifiedTopology: true,
});
const connection = mongoose.connection;
connection.once("open", () => {
  console.log("MongoDB database connection established successfully");
});

const myRouter = require("./routes/example.js");

app.use(passport.initialize()); // used to attatch token to request headers
require("./config/passport")(passport); 

app.use("/example", myRouter);

if (process.env.NODE_ENV === "production") {
  app.use(express.static("client/build"));
  app.get("*", (req, res) => {
    res.sendFile(path.resolve(__dirname, "client", "build", "index.html"));
  });
}

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...